Imagine the code:
ls || echo "Unable to execute ls (returned non zero)"
What if I needed to execute more commands like:
ls || echo "this is echo 1" <some operator> echo "this is echo 2" <some operator> exit 1
in C (assumming I have a function ls
) I could do (even if it looks insane):
ls() || (command1() && command2());
but I doubt I can use parentheses like this in bash.
I know I can create a Bash function that would contain these commands, but what if I needed to combine this with exit 1
(exit in a function would exit that function, not whole script)?
Ampersand Operator (&) Sixth Bash shell command line Chaining Operator (Linux operator) is Ampersand Operator (&). Ampersand Operator is a kind of operator which executes given commands in the background. You can use this operator to execute multiple commands at once.
Running Multiple Commands as a Single Job We can start multiple commands as a single job through three steps: Combining the commands – We can use “;“, “&&“, or “||“ to concatenate our commands, depending on the requirement of conditional logic, for example: cmd1; cmd2 && cmd3 || cmd4.
Logical OR Operator ( || ) in Bash It is usually used with boolean values and returns a boolean value. It returns true if at least one of the operands is true. Returns false if all values are false.
You can group multiple commands within { }
. Saying:
some_command || { command1; command2; }
would execute command1
and command2
if some_command
exited with a non-zero return code.
{}
{ list; }
Placing a list of commands between curly braces causes the list to be executed in the current shell context. No subshell is created. The semicolon (or newline) following list is required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With