Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use multiple commands after "||" in Bash

Tags:

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)?

like image 240
Petr Avatar asked Nov 06 '13 08:11

Petr


People also ask

How do you chain multiple commands in Bash?

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.

How do you run multiple commands in one line?

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.

What is || in bash script?

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.


1 Answers

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.

like image 64
devnull Avatar answered Sep 24 '22 15:09

devnull