Join my Laravel for REST API's course on Udemy 👀

Bash: Assign default value for a positional parameter

July 22, 2022  ‐ 1 min read

In a bash script that uses parameters we can set a default value for our arguments. We can do so by making use of a special way of parameter expansion: ${parameter:-default}.

If the parameter is not set or null bash expands the parameter as default. Otherwise the value of the parameter is maintained.

For example, let's assume we have the following script.

echo "$var, user"

If we call our script without positional parameters, the value $1 is not set and therefore we set the variable var to the default of "Hello".

$ ./script
Hello, user

If we instead call our script with "Goodbye" as the first positional argument, var is expanded to this value.

$ ./script Goodbye
Goodbye, user