Reputation: 8518
From "Process all arguments except the first one (in a bash script)" I have learned how to get all arguments except the first one. Is it also possible to substitute null with another value, so I can define a default value?
I've tried the following, but I think I don't get some little detail about the syntax:
DEFAULTPARAM="up"
echo "${@:2-$DEFAULTPARAM}"
Here are my test cases:
$ script.sh firstparam another more
another more
$ script.sh firstparam another
another
$ script.sh firstparam
up
Upvotes: 2
Views: 2974
Reputation: 126108
bash doesn't generally allow combining different types of special parameter expansions; this is one of the combos that doesn't work. I think the easiest way to get this effect is to do an explicit test to decide whether to use the default value. Exactly how to do this depends on the larger situation, but probably something like this:
#!/bin/bash
DEFAULTPARAM="up"
if (( $# >= 2 )); then
allbutfirstarg=("${@:2}")
else
allbutfirstarg=("$DEFAULTPARAM")
fi
echo "${allbutfirstarg[@]}"
Upvotes: 0
Reputation: 786329
You cannot combine 2 expressions like that in bash
. You can get all arguments from position 2 into a separate variable and then check/get default value:
defaultParam="up"
from2nd="${@:2}" # all arguments from position 2
echo "${from2nd:-$defaultParam}" # return default value if from2nd is empty
PS: It is recommended to avoid all caps variable names in your bash script.
Testing:
./script.sh firstparam
up
./script.sh firstparam second
second
./script.sh firstparam second third
second third
Upvotes: 3