yupe
yupe

Reputation: 127

Use logical and && and logical or || construct substitute of if/else statement

I am thinking about if there are just two types of conditions (0, 1), can we use the following code to substitue if/else construct in shell in one line.
This is first expression I figured out, while it need the condition that op1 won't fail.

[ condition ] && op1 || op2
# condition = true then do op1, if op1 success too, then won't execute op2
# condition = false then do op2, won't execute op1, execute op2 directly.

So I figure out the second version

[ condtion ] && ( op1 || 1 ) || op2

What I think is ( op1 || 1 ) will always be true instead of considering op1's result. But I am not sure if it will work correctly? Anyone has more ideas?

Upvotes: 0

Views: 103

Answers (1)

KamilCuk
KamilCuk

Reputation: 140970

But I am not sure if it will work correctly?

No, there is no such command as 1. You can use true or :.

Also, ( will spawn a subshell. Use { op1 || :; }.

Anyone has more ideas?

Do not write unreadable code that you have to think about how it works and are not sure. Write an if. Everyone understands an if. It's simple, readable, you know what's going on. Just write an if, do not use && || when you mean an if.

if [ condtion ]; then op1; else op2; fi

hether [ condition ] && {op1 || :;} || op2 equals to if condition; then op1; else op2; fi or not ?

The if condition exits with the exit status of last command executed in the body, or if body was not executed, with 0. The && || will exit with 0.

$ true && { false || :; } || false; echo $?
0
$ if true; then false; else false; fi; echo $?
1

Upvotes: 3

Related Questions