0

I have come across an assignment like this which I have never seen before, ": ${var=$*}". The assignment can also be done like var=$*, but can anyone explain about the above what is being done. I tried to search for it but got nothing.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Check
  • 169
  • 1
  • 1
  • 9
  • 4
    Bash manual: [special parameters](https://www.gnu.org/software/bash/manual/bash.html#Special-Parameters) for `$*`; [Bourne shell built-in commands](https://www.gnu.org/software/bash/manual/bash.html#Bourne-Shell-Builtins) for `:` command; [shell parameter expansion](https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion) for `${var=$*}`. Although I cited the Bash manual, for this notation, a Korn shell manual would give the same information; so would the POSIX shell specification. – Jonathan Leffler Jul 20 '20 at 05:09

2 Answers2

1

Explication:

For example:

    A="value1"
    B=${A="value2"}
    echo $B  ->  value1

Now, when the variable A is not defined, it retrieves the value 'value2'

    unset A
    B=${A="value2"}    
    echo $B  ->  value2
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
mchelabi
  • 154
  • 5
0

Lets look at this line step by step:

  • : argument : This only executes the expansions of argument. The colon command is generally not useful, but can be used for parameter validation or initialisation via parameter expansion. It is also used to run infinite while loops.

  • ${var=word} The argument in the above expansion is of the form ${var=word}. This is identical to ${var:=word} with the only difference that the former tests if var is unset while the latter tests if var is unset or null. If the condition applies, var is assigned with the value of word

  • $* The value of word in the above is now the expansion of $*. It expands to a single string of the form $1c$2c$3c...$ where $n are the values of the command arguments and the value of c expands to the first character of the variable IFS.

Having this all said, this command is equivalent to the following line which uses classic programming jargon:

if [ -z ${var+x} ]; then var="$*"; fi

See How to check if a variable is set in Bash?

kvantour
  • 25,269
  • 4
  • 47
  • 72
  • The compact notation is very readble — more so than the `if` statement — once you are familiar with it. Especially as you're using an alternative to `${var=val}` in the `if`. – Jonathan Leffler Jul 20 '20 at 14:07
  • @JonathanLeffler you are correct. I've rewritten the sentence a bit. – kvantour Jul 20 '20 at 14:10