Bijou Trouvaille
Bijou Trouvaille

Reputation: 9444

How to assign a variable inside a bash test command?

ok="1"
test -f no_such_file || (ok='0' && echo ggg)
> ggg
echo $ok
> 1

Why is $ok still 1? How can I make it 0 in this situation?

Upvotes: 1

Views: 971

Answers (2)

William
William

Reputation: 4935

Try writing it this way:

test -f no_such_file || { ok='0'; echo ggg; }

The { } will give you grouping but won't start a subshell. The && wasn't useful in this case so I replaced it with ';'.

Upvotes: 3

Alex
Alex

Reputation: 11100

The reason is that (ok='0' && echo ggg) is run in a subshell because it is enclosed in ()s. If you run it without the parentheses:

ok="1"
test -f no_such_file || ok='0' && echo ggg
> ggg
echo $ok
> 0

You would have to adjust your logic to leave assignment statements outside of ()s

Upvotes: 2

Related Questions