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?
CodePudding user response:
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