What is the meaning of "var=${str=expr}" in linux shell? Who can explain it for me specifically?
2 Answers
See "Parameter Expansion" in man bash
:
${parameter:=word}
Assign Default Values. If parameter is unset or null, the expansion of word is assigned to parameter. The value of parameter is then substituted. Positional parameters and special parameters may not be assigned to in this way.
The colon is explained above:
When not performing substring expansion, using the forms documented below, bash tests for a parameter that is unset or null. Omitting the colon results in a test only for a parameter that is unset.
Evidence:
var=${str=expr}
echo $var
echo $str
Output:
expr
expr
-
Very good explanation! "Omitting the colon results in a test only for a parameter that is unset." seems right as well in ${parameter:=word}, ${parameter:-word} and ${parameter:+word}. Am I right?@chroba However, it is not very often to see the form without colon and therefore many thanks for your answer. Jul 30, 2014 at 8:52
In bash you can use $( ) to start a task in a subshell.
Example:
#!/usr/bin/env bash
foo=${ls}
echo $foo
This script will fill the variable $foo with the result of ls
.
(and echo $foo
will show you the content).
Now to your more specifiuc question. I did not know the result either so I tested it, assuming that with 'linux shell' you means bash, which is the default shell on my linux distributions.
I created the following file:
#!/usr/bin/env bash
foo=${str="test 1 2 3"}
echo $foo
and ran it:
> ./test t
test 1 2 3
It appears to assign the value iun the string (or in your expression) to the variable and to return that value to the parent script.
To recap:
- A new shell will be started
- That new shell will run the command
str=expr
- The parent shell will get the result as output.
- The parent shell stores that result in $var.
-
You're confusing
$( )
, the subshell operator, with${ }
, the variable expansion operator. They do the same thing in Makefiles but not in shell. Jul 29, 2014 at 11:16 -
var=${str:=expr}
? What shell specifically,bash
,zsh
,fish
?