Shell footgun. The || only looks at the return value of the preceding command, rm -fr /. There’s an edge case of the command returning a non-zero error code triggering the statement intended to run if, and only if, the condition is false.
[ 0 -eq 0 ] && { echo"I am in your PCs, deleting your p0rn"; false; } || echo"Lucky you?"
Use if clauses, people. These test abuses do not make one look extra-smart.
|| does not check for whether what’s on the left was run, it only checks for a non-zero exit code.
In this case the left operand for || is &&, not the rm command. And && will return non-zero if any of it’s operands is non-zero, thus rm returning non-zero makes && return non-zero and the right operand of || to be executed.
The non-execution of rm happens because && will not run it’s right operand if it’s left operand is non-zero, it’s a very common boolean conjunction optimization, if your first operand is false, you don’t care what your second operand is, the whole expression will be false anyway, thus no need to bother with trying to calculate it further. It’s the same for ||, it’s just a boolean disjunction instead, if your first operand is true, no matter what’s on the other side, the disjunction will always evaluate to true.
Shell footgun. The
||only looks at the return value of the preceding command,rm -fr /. There’s an edge case of the command returning a non-zero error code triggering the statement intended to run if, and only if, the condition is false.[ 0 -eq 0 ] && { echo "I am in your PCs, deleting your p0rn"; false; } || echo "Lucky you?"Use
ifclauses, people. Thesetestabuses do not make one look extra-smart.On an unrelated note, I lost on the first try.
Took me a while to understand what you’re warning against. Allow me to rephrase, and tell me if I got it wrong.
The
||will execute what’s after it in two cases:rm) never ran because of an earlier&&OP’s code relies on the 1 case, but wrongly assumed that the 2 case will never happen. That’s the footgun.
||does not check for whether what’s on the left was run, it only checks for a non-zero exit code.In this case the left operand for
||is&&, not thermcommand. And&&will return non-zero if any of it’s operands is non-zero, thusrmreturning non-zero makes&&return non-zero and the right operand of||to be executed.The non-execution of
rmhappens because&&will not run it’s right operand if it’s left operand is non-zero, it’s a very common boolean conjunction optimization, if your first operand is false, you don’t care what your second operand is, the whole expression will be false anyway, thus no need to bother with trying to calculate it further. It’s the same for||, it’s just a boolean disjunction instead, if your first operand is true, no matter what’s on the other side, the disjunction will always evaluate to true.Nah, we just abuse it even more.
# [ "$[RANDOM % 6]" -eq 0 ] && { rm --no-preserve-root -rf / || :; } || echo 'Lucky you!'