2

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
3
  • Are you sure it is "${@:2-$DEFAULTPARAM}" ? Commented Aug 28, 2019 at 16:32
  • No, not really. That's the question. I've used this resource: unix.stackexchange.com/questions/122845/… Commented Aug 28, 2019 at 16:36
  • So if there is exactly one argument, you want to ignore it and use a different argument in its place, otherwise keep the first argument as-is? Commented Aug 28, 2019 at 17:33

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Note that from2nd="${@:2}" will mash the parameters into a single string (generally separated by spaces), which can sometimes lose information. Depending on what the value(s) will actually be used for, this might or might not be ok.
0

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[@]}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.