If you use Linux daily, you will know that the command line is the most powerful tool when you working with files, installing and configuring system software, and running them. It becomes even more efficient if you run two or more commands at once on the command line and save a good deal of time.
In this tutorial, we’ll see the different ways in which we can combine and execute multiple Linux commands efficiently in one single line.
; |
cmd1; cmd2 | The “;” operator runs all commands regardless of whether the earlier ones are failed or not. |
&& |
cmd1 && cmd2 | The “&&” operator carries out the second command only if the preceding command executes successfully. |
|| |
cmd1 || cmd2 | The “||” operator executes the second command only if the precedent command returns an error. |
Let me explain to you in more detail how you can execute multiple commands in Linux in one go.
1. Using Semicolon (;) Operator to Run Multiple Linux commands
The semicolon (;)
operator enables you to run one or more commands in succession, regardless of whether each earlier command succeeds or not. For example, run the following three commands on one line separated by semicolons (;)
and hit enter.
$ ls ; pwd ; du ; whoami
This will show you a listing of the current directory ( ls ), show which directory you’re currently in ( pwd ), print the disk usage of files (du), and display your account login name ( whoami ) all at once.
2. Using AND (&&) Operator to Run Multiple Linux Commands
In some scenarios, you want to make sure that the second command only executes if the first command is executed successfully. For example, run the two commands separated by (&&)
operator, which is two ampersands.
$ sudo apt update && sudo apt upgrade
Here the first command updates the package database lists for packages that need upgrading. If there are no errors, it will execute the second command that will upgrade all the packages to a newer version.
I highly recommend using the (&&)
operator rather than using (;)
semicolon operator most of the time. This assures that you don’t do anything terrible. For example, if you run the following command to change to a directory and then delete everything recursively in that directory, you could end up destroying your system if the directory change didn’t take place.
$ cd /my_directory ; rm -Rf *
3. Using (||) Operator to Run Several Linux Commands
At times you might want to run a second command only if the first command returns an error. To do this, you need to use (||)
operator. For example, you want to verify that if the MyFolder directory exists and create it if it doesn’t.
$ [ -d ~/MyFolder ] || mkdir ~/MyFolder
In the above example, the MyFolder directory does not exist, so the second command creates the directory.
Conclusion
In this article, we have learned the three useful ways in which we can combine and run multiple Linux commands in the command line productively.