Bash empty string / command

I found a strange thing in bash, and I cannot figure out how it works.

[test ~]$ a=""
[test ~]$ $a && echo 1
1

[test ~]$ $a
[test ~]$ echo $?
0

Why does $ a (empty) return 0? Does it somehow transform into an empty team? If I add quotes or write an empty string before &&, it will return an error. While an empty command returns 0.

[test ~]$ "$a" && echo 1
-bash: : command not found

[test ~]$ "" && echo 1
-bash: : command not found

[test ~]$ `` && echo 1
1

So what happens when I type $ a?

+4
source share
2 answers

You seem to be confused bashwith another programming language. The variables are replaced, then what is left is executed.

"$a"

This is the contents a, between quotation marks. ais empty, so this is equivalent to:

""

. " ." , ( 0), - && echo 1 - .

...

``

... , , , . ( $(), script.) ...

`echo "foo"`

... ...

foo

..., . , ...

``

... ...

 <empty>

... " " ( ).

a echo 1 , a , test:

test -n "$a" && echo 1

test, [, ]...

[ -n "$a" ] && echo 1

... bash -ism [[, "" , , , , $a ...

[[ -n $a ]] && echo 1

... , , ...

if [[ -n $a ]]
then
    echo 1
fi

. :

$a && echo 1

, &&. , . bash :

$a

...

<empty>

... "", . ...

&& echo 1

... , .;-) (Tricky, , , cookie .)

+5
a=""

a="                       " #a long empty string

$> $a

0

$> $noExistVar

0.

"", . , 10 , , .

$>       && echo 1

, bash , .

$> $notExistVar && echo 1

, bash $whatever, . "" , , 0, ( , enter ), , 0, cmd &&.

guess, bash. , , .

the $> " " && echo 1, , , .

0

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


All Articles