Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

${1:+"$@"} in /bin/sh

Tags:

shell

People also ask

What is $@ in .sh file?

$@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

What does ${ 1 mean in shell script?

It says, “If there is at least one argument ( ${1+ ), then substitute in all the arguments ( “$@” ) preserving all the spaces, etc. within each argument.

What is $@ and $* in shell script?

"$@" Stores all the arguments that were entered on the command line, individually quoted ("$1" "$2" ...). So basically, $# is a number of arguments given when your script was executed. $* is a string containing all arguments. For example, $1 is the first argument and so on.

What is ${ in shell script?

Here are all the ways in which variables are substituted in Shell: ${variable} This command substitutes the value of the variable. ${variable:-word} If a variable is null or if it is not set, word is substituted for variable.


'Hysterical Raisins', aka Historical Reasons.

The explanation from JesperE (or the Bash man page on shell parameter expansion) is accurate for what it does:

  • If $1 exists and is not an empty string, then substitute the quoted list of arguments.

Once upon 20 or so years ago, some broken minor variants of the Bourne Shell substituted an empty string "" for "$@" if there were no arguments, instead of the correct, current behaviour of substituting nothing. Whether any such systems are still in use is open to debate.

[Hmm: that expansion would not work correctly for:

command '' arg2 arg3 ...

In this context, the correct notation is:

${1+"$@"}

This works correctly whether $1 is an empty argument or not. So, someone remembered the notation incorrectly, accidentally introducing a bug.]


To quote the relevant portion of man bash for the information that Jonathan Leffler referred to in his comment:

When not performing substring expansion, bash tests for a parameter that is unset or null; omitting the colon results in a test only for a parameter that is unset.

(emphasis mine)


From the bash man page:

   ${parameter:+word}
          Use Alternate Value.  If parameter is null or unset, nothing  is
          substituted, otherwise the expansion of word is substituted.

So, "$@" is substituted unless $1 is unset. I can't see why they couldn't have just used "$@".