Quite often, I have to run multiple commands at once to save time. Most commonly, I would create a directory and switch to it in one go. So how do I do it? There are three ways you can run multiple commands in one go in Linux. You can use one of these operators between commands: &&, || and ; Each works differently, so let’s explore them.
&& Operator
Example: pwd && echo "second command after pwd" && cd ~/Documents
The command after && only runs if the previous command succeeded. What’s a successful command? A successful command execution returns an exit code of 0. How can you check your exit code? Run echo $?
to check the exit status of the last command. If you run echo $?
after any valid command like pwd
or ls
, the exit code would be 0.
Example when a command after && doesn’t execute: pwd && res && cd ~/Documents
Here, my first pwd
was successful, but the command res
was invalid, so the third command didn’t execute.
|| Operator
|| is totally opposite to &&, the command after || runs if the previous command failed. Example: cd ~/Doddd || echo "second command"
Unlike &&, the previous command has to have a non-zero exit code for the next command to run. For instance: cd ~/Documents || echo "second command"
Since cd ~/Documents
is a valid command, echo "second command"
didn’t run.
; Operator
This doesn’t care if the previous command fails or succeeds and it will run all the commands regardless of their exit status. Example: pwd ; wd ; echo "third command"
Here, the second command failed, but it didn’t matter—echo "third command"
executed regardless.
Combining &&, || and ;
You can certainly combine these operators to create more complex command sequences.
Example: pwd && cd ~/Doddd || echo "Not Found" ; echo "doesn't matter"