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
Robin
  • 8,162
  • 7
  • 56
  • 101
  • Are you sure it is `"${@:2-$DEFAULTPARAM}"` ? – anubhava Aug 28 '19 at 16:32
  • No, not really. That's the question. I've used this resource: https://unix.stackexchange.com/questions/122845/using-a-b-for-variable-assignment-in-scripts – Robin Aug 28 '19 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? – chepner Aug 28 '19 at 17:33

2 Answers2

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 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. – Gordon Davisson Aug 28 '19 at 16:58
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[@]}"
Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151