Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"${1-}" vs "$1"

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?

like image 226
intuited Avatar asked Apr 17 '11 11:04

intuited


People also ask

What does ${ 1 mean in bash script?

$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#*=}"

What does [- Z $1 mean in bash?

$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.

What does$ 1 mean in shell?

$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)

What is$ 1 in shell script?

$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.


2 Answers

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.

like image 112
Gilles 'SO- stop being evil' Avatar answered Oct 12 '22 11:10

Gilles 'SO- stop being evil'


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.

like image 28
user unknown Avatar answered Oct 12 '22 10:10

user unknown