'Default values for the arguments to a Unix shell script?

Normally when a parameter is passed to a shell script, the value goes into ${1} for the first parameter, ${2} for the second, etc.

How can I set the default values for these parameters, so that if no parameter is passed to the script, we can use a default value for ${1}?



Solution 1:[1]

You could consider:

set -- "${1:-'default for 1'}" "${2:-'default 2'}" "${3:-'default 3'}"

The rest of the script can use $1, $2, $3 without further checking.

Note: this does not work well if you can have an indeterminate list of files at the end of your arguments; it works well when you can have only zero to three arguments.

Solution 2:[2]

#!/bin/sh
MY_PARAM=${1:-default}

echo $MY_PARAM

Solution 3:[3]

Perhaps I don't understand your question well, yet I would feel inclined to solve the problem in a less sophisticated manner:

                     ! [[ ${1} ]]   &&   declare $1="DEFAULT"

Hope that helps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 UNIX Rox