Why does this bash construct work? (Parameter-substitution)

the code: ${non_existent_variable:+whatever} && echo "it works"

Result it works. But why? the part before && evaluates the empty string. However, an attempt to execute: && echo testgives an error.

I have this by accident, trying to create a triple operator replacement for bash with different results for the set and unset variable. It works this way, but I'm lost why it works at all.

PARAM=$(${tested_variable:+false} && echo var_exists || echo var_empty)

+4
source share
3 answers

In the section of section 2.9.1 of the POSIX specification :

" " , , .

2.9.1 :

, , Command Search and Execution. , , . .

, , .. , 0.

&&. :

&& echo it works

- "" . - , , ${non_existent_variable:+whatever}.

+6

, , &&, - (.. $?), , . (, , ), .

, $(echo "") && echo test , . echo 0 (.. true), 0, .

+2
${non_existent_variable:+whatever} && echo "it works"

( " ), [1] AND and OR lists:

AND OR , && || . AND OR . AND

         command1 && command2

command2 , , 1 .

: command1, true, command2 &&.

, :

true && echo "it works"

:

: && echo "it works"

, ( ):

$ a=''
$ $a && echo "it works"

, null string, :
man bash:

, , . . , - . , 0.

:

$ a=''
$ $a; echo "$?"
0

false :

$ false; $a; echo "$?"
0

, "$a" ( ):

$ "$a"
bash: : command not found

[1] bash, bash. , , .

+1
source

Source: https://habr.com/ru/post/1652101/


All Articles