1 answer
The dash, -
, is part of a Parameter Expansion syntax that tells Bash to check for existence of the preceding parameter, a.k.a. whether it is "set", substituting whatever follows if it isn't. For the particular case of ${2-}
, an empty string will be substituted if the second positional parameter doesn't exist.
From the previously linked online Bash Manual:
if the colon is included, the operator tests for both parameter’s existence and that its value is not null; if the colon is omitted, the operator tests only for existence.
So ${2-}
means the same thing as ${2}
, except that Bash will test for existence of that parameter thanks to the presence of -
. If a colon were included as well, e.g. ${2:-}
, Bash would additionally check that the value of the parameter is not null.
unset v
echo "${v-hi}"
echo "${v:-hi}"
v=""
echo "${v-hi}"
echo "${v:-hi}"
v=123
echo "${v-hi}"
echo "${v:-hi}"
# OUTPUT:
# > this_script.sh
# hi
# hi
# <- empty string
# hi
# 123
# 123
NOTE: This syntax is very similar to a particular Substring Expansion syntax: ${parameter:offset}
. If your offset
is negative, you must include a leading space to disambiguate from the Parameter Expansion syntax.
unset string
echo "${string:-3}"
echo "${string: -3}"
string=abcdefg
echo "${string:-3}"
echo "${string: -3}"
# OUTPUT:
# > this_script.sh
# 3 <- alternative "3"
# <- substring of an empty string
# abcdefg <- alternative "3" not needed since string is set and not null
# efg <- substring, last three characters
As for ${2}
itself: It simply refers to the second Positional Parameter, whether a parameter of the script itself, or of a local function. In this case, since it's a single digit, it is equivalent to $2
.
# Second argument to the script
echo "$2"
func() {
# Second argument to a function
echo "$2"
}
func x y
# OUTPUT:
# > this_script.sh a b
# b
# y
In the example you gave, it seems the intent is to append the second argument to the array called "excludes", or append an empty string if there is no second argument. In other words, whether the argument is omitted or specified as an empty string, the result will be the same.
1 comment thread