How to write a Bash script
Help 7 / 9
User input

Optional parameters

Instead of making the name required, we can also make it optional and give it a default value using the weird :- notation (there’s a lot of weird things about Bash, wait till you hear about arrays):

#!/bin/bash
usage="Usage: ./hello.sh greeting [name]"
greeting=${1?$usage}
name=${2:-World}

echo "$greeting $name"

Now run the script again without the second parameter to see if it picks up the default value:

./hello.sh Hello

But if you specify a second parameter, it overwrites the default, as expected:

./hello.sh Hello Robert

Loading...