1

What is the meaning of "var=${str=expr}" in linux shell? Who can explain it for me specifically?

4
  • 1
    Are you sure it's not var=${str:=expr}? What shell specifically, bash, zsh, fish?
    – Daniel Beck
    Jul 29, 2014 at 10:33
  • 2
    @DanielBeck: Both are valid in POSIX /bin/sh; the one without colon is just much less useful and rarely seen in wild. Jul 29, 2014 at 11:15
  • @grawity - Thanks for that: I had reached the conclusion that in bash = was behaving as :=, but I did not know about the POSIX specification. The bash manual pages make no mention of it.
    – AFH
    Jul 29, 2014 at 11:30
  • @grawity I can not find useful information about that in man page. That's why I ask for help here. Jul 30, 2014 at 1:51

2 Answers 2

4

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
1
  • 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
-3

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.
2
  • 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
  • Ah. Darn. That and a poor screen in which { and ( look the same.
    – Hennes
    Jul 29, 2014 at 11:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .