1

I have a bash script that uses $1 to process a command line argument.

I want to modify this script to work even when a command line argument isn't given; in that case I want the script to use a default value.

I don't know how to do this; basically I figure I need to replace $1 with my own variable and have a line at the start of the program that checks whether a value was passed for $1, and if not to use the default that I'll provide. But I don't know the syntax for that. Can anyone help me?

2 Answers 2

7

Use parameter expansion:

var=${1:-default}

From the given link:

${parameter:-word}

If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

See an example:

$ echo "$v"

$ t=${v:-hello}
$ echo "$t"
hello
$ v=2
$ t=${v:-hello}
$ echo "$t"
2

And note also that ${var:-value} and ${var-value} are not the same: What is the difference between ${var:-word} and ${var-word}?.

Sign up to request clarification or add additional context in comments.

Comments

1

Try:

echo "${1:-"my default"}"

in your script (e. g. foo.sh) to see the effect of the :- modifier.

Notice that in case you pass an empty string to your script, also the default kicks in:

$ ./foo.sh ""
my default

So you cannot distinguish the empty string from a not-given argument this way.

In case you need to have that distinction, you should rely on $# to tell you the number of arguments:

if [ $# = 0 ]
then
  echo "my default"
else
  echo "$1"
fi

=>

$ printf "[%s]\n" "$(./foo.sh "")"
[]

5 Comments

Actually, I didn't know about ${a-b} yet and would consider it superior to using $#.
@cdarke so does [ $# -eq 0 ]
@cdarke Absolutely correct. In these cases I prefer the first as it results in the same, is probably cheaper, is less to type, etc. But as soon as comparisons like (( $# > 5 )) are involved, the numeric syntax is probably nicer to read.
@User112638726 true, old Bourne shell syntax. But = was used, not -eq.
I always considered -eq, -lt, etc. a clutch and a second-best solution. Using =, >=, etc. help with their visual to prevent errors, so I prefer them if possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.