The code for git bash completion, specifically the function __gitcomp
, uses parameter expansions like "${1-}"
. This appears to be similar to "$1"
. What is the difference?
Also: where is this documented in the bash
manual?
$1 is the first positional parameter passed to the shell. The general format can be written as ${var#patt} too, where patt is matched (shortest match from start) in $var and deleted. Example: var="first=middle=last" echo "${var#*=}"
$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.
$1 is the first command-line argument passed to the shell script. Also, know as Positional parameters. For example, $0, $1, $3, $4 and so on. If you run ./script.sh filename1 dir1, then: $0 is the name of the script itself (script.sh)
$1 - The first argument sent to the script. $2 - The second argument sent to the script. $3 - The third argument... and so forth. $# - The number of arguments provided. $@ - A list of all arguments provided.
First, recall that ${foo-bar}
expands to the value of foo
, like $foo
or ${foo}
, except that if foo
is unset, ${foo-bar}
expands to bar
($foo
expands to the empty string if foo
is unset). There is a more often-used variant of this syntax, ${foo:-bar}
, which expands to bar
if foo
is unset or empty. (This is explained in the manual if you look closely enough: search for :-
, and note the sentence “Omitting the colon results in a test only for a parameter that is unset.” above.)
For a positional parameter $1
, ${1-bar}
expands to bar
if $1
is unset, that is, if the number of positional parameters is less than 1. Unless the positional parameters have been changed with set
or shift
, this means that the current function, or if not applicable the current script, has no parameter.
Now when bar
is empty, ${1-}
looks like a useless complication: the expansion is that of $1
, except that when $1
is unset, the expansion is empty, which it would be anyway. The point of using ${1-}
is that under set -u
(a.k.a. set -o nounset
), a plain $1
would result in an error if the parameter was unset, whereas ${1-}
always successfully expands to the empty string if $1
is unset.
echo "${foo-default}"
Prints $foo, if foo is defined, and 'default', if foo is undefined. So I conclude
"${1-}"
is empty, if the first argument to the script is not defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With