You have a shell script that takes arguments supplied on the command line. You’d like to provide default values so that the most common value(s) can be used without needing to type them every time.
Use the ${:-} syntax when referring to the parameter, and use it to supply a default value:
FILEDIR=${1:-/tmp}
There are a series of special operators available when referencing
a shell variable. This one, the : -operator, says that if $1
is not set or is null then it will use what
follows, /tmp
in our example, as the
value. Otherwise it will use the value that is already set in $1
. It can be used on any shell variable, not
just the positional parameters (1, 2, 3, etc.), but they are probably
the most common use.
Of course you could do this the long way by constructing
an if
statement and
checking to see if the variable is null or unset (we leave that as an
exercise to the reader), but this sort of thing is so common in shell
scripts that this syntax has been welcomed as a convenient
shorthand.
bash manpage on parameter substitution
Learning the bash Shell by Cameron Newham (O’Reilly), See Also-Discussion
Classic Shell Scripting by Nelson H.F. Beebe and Arnold Robbins (O’Reilly), pages 113–114
3.144.47.218