Chris Kerr
Chris Kerr

Reputation: 161

Bash optional parameters and setting to default

I have a bash upload script which looks like this -

if [ $# -lt 2 ] 
then
   echo usage: $0 /path/to/mvn /path/to/libs [procs] [groupId]
fi

MVN_EXE=$1
LIB_DIR=$2
PROCS=10
GROUPID=$4:-'default'

if [ $# -gt 2 ] 
then
  PROCS=$3
fi

I want the GROUPID to be the 4th arg or to be set automatically to 'default'. Could I be advised on the correct syntax for this? A google search has given me this so far. Would I then need to add an additional if search along the lines of -

if [$# -gt 3]
then
PROCS=$3
GROUPID=$4
fi

or just replace the original if statement with the new version?

Thanks

Upvotes: 1

Views: 73

Answers (2)

lynxlynxlynx
lynxlynxlynx

Reputation: 1433

You just forgot the curly braces. You can use them to avoid the final if statement too:

if [ $# -lt 2 ] 
then
   echo usage: $0 /path/to/mvn /path/to/libs [procs] [groupId]
fi

MVN_EXE=$1
LIB_DIR=$2
PROCS=${3:-10}
GROUPID=${4:-'default'}

Upvotes: 4

anubhava
anubhava

Reputation: 786359

Correct syntax is:

GROUPID=${4:-'default'}

Upvotes: 0

Related Questions