Run Multiple Linux Commands in One Go
In this quick, beginner's tip, learn to run multiple Linux commands one after another in a single command.
There are times when you want to execute multiple commands but don't want to wait for one to end so that you can run the next.
Luckily, Linux gives you multiple ways to run multiple commands and in this tutorial, I will show you three ways to do so:
- Using the semicolon (;) operator
- Using the AND (&&) operator
- Using the OR (||) operator
1. Run multiple commands using a semicolon
Chaining multiple commands using a semicolon is the most famous method of running multiple commands and there's a reason why.
You can add any command in the chain of commands as every command will be executed individually and does not depend on the status of the previous command execution.
Command_A ; Command_B ; Command_C
As you can see, all I did is separate two commands with space and one semicolon.
Pretty easy. Right? Now, let's have a look at an example:
cr ; pwd ; hostname
Here, I've used one faulty command
cr which sure gave me an error but the other two commands executed independently.
2. Run multiple commands using AND (&&) operator
&&, the second command will only be executed if the first runs with no errors.
If you want to run multiple commands in such a way that if one of the commands returns an error, the later part of the chain won't be executed, you can use the AND operator.
To use execute multiple commands with the AND operator, you'd have to follow the following syntax:
Command_A && Command_B && Command_C
For example, here, I tried 3 commands and the middle one is faulty:
pwd && cr && hostname
As you can see, it gave me an error for the second command, and the third command was not executed.
3. Run multiple commands using OR (||) operator
The whole idea of the OR operator lies in its name.
It will execute only one of the two commands that are chained together.
But how it will decide which one to execute and which to not? Simple.
If the first command gives an error then it will execute the 2nd command.
Think of it as an if-else statement.
To use the OR operator to run multiple commands, it needs to be executed in the following manner:
Command_A || Command_B
For example, here, I used the cat command to print the contents of the
New.txt file and if there is no such file, the second command, touch will be used to create one:
cat New.txt || touch New.txt
As you can see, first, it gave me an error, and later on, it executed the touch command to create a new file.
Run commands in the background and foreground
If taking care of command execution is the main priority, running them in the background or foreground can do miracles for you.
Sounds interesting? Here's how you do it:
I hope you will find this guide helpful.