The default Bash variable does not work if you follow the channel (Bash error?)

I just discovered weird behavior in bashwhich I don't understand. Expression

${variable:=default}

sets the variablevalue default, if not already set. Consider the following examples:

#!/bin/bash
file ${foo:=$1}
echo "foo >$foo<"
file ${bar:=$1} | cat
echo "bar >$bar<"

Conclusion:

$ ./test myfile.txt
myfile.txt: ASCII text
foo >myfile.txt<
myfile.txt: ASCII text
bar ><

You will notice that a variable is fooassigned a value $1, but the variable is barabsent, although the result of its default is presented to the command file.

If you delete a harmless channel catfrom line 4, and then start it again, then both fooand barget the value$1

Am I missing something here, or is this a potential mistake bash?

(GNU bash version 4.3.30)

+4
2

file . file , $b $1 .

:

#!/bin/bash
file ${foo:=$1}
echo "foo >$foo<"

: "${bar:=$1}"     # Parameter Expansion before subshell

file $bar | cat
echo "bar >$bar<"
+5

. , , , , , , . , - , , .

bash:

> foo=5
> bar='$foo'
> echo "$bar"
$foo
# $bar expands to '$foo' before the subshell is created, but then `$foo` expands to 5
# during the "normal" round of parameter expansion.
> echo "$bar" | cat
5

, bash , , . , , , . , , .

- , POSIX, . bash , , , , . (bash 4.2 lastpipe, , .)

+2

All Articles