Run Multiple 'Cmds' at once in Linux.

This is the tenth in a series of posts featuring Protips, tips, tricks, hacks, and secrets provided by Our Team 🙊 — We want to share our top tips for the growing and thriving Linux community out there. Because sometimes you need a little help...

Run Multiple 'Cmds' at once in Linux.



If you’re a newbie in Linux, chances are that you might be looking for methods to execute multiple commands at a time on your terminal shell, such as downloading, installing applications, and restarting a service. Running two or more commands in one line can save you a good deal of time and help you become more efficient and productive.

🎧



There are three different ways to combine and execute multiple commands in one line in Linux.


The Semicolon (;) Operator

The semicolon (;) operator allows you to execute multiple commands in succession, regardless of whether each previous command failed or not. This executes all commands one after another.

$ ls; pwd; cd venus; whoami; date; uptime

OUTPUT

1123.jpg  backup_cron.txt  Desktop
/home/uranus
cd: no such file or directory: venus     <<<
uranus
Fri 10 Dec 2021 01:07:13 PM UTC
 13:07:13 up 2 min,  1 user,  load average: 0.91, 0.68, 0.27

As you can see, if one command fails in the chain, the remaining commands will always execute as shown above in the OUTPUT.


The Logical AND (&&) operator

Sometimes you want to ensure, that the next command only runs when the previous command ends successfully. This is where the logical AND operator (&&) comes in handy.

$ sudo apt update && sudo apt -y upgrade

OUTPUT

Here, the first command sudo apt update first refreshes the package database cache; if there is no error it will then upgrade all the packages that have newer versions available.


The Logical OR Operator (||)

The logical OR operator will decide what to do if the prior command fails or returns an error.
Similarly, if cmd#1 fails, cmd#2 runs. If cmd2 runs successfully, cmd#3 won’t run.

$ cd top || cd tips || ls -lhrt

OUTPUT

cd: no such file or directory: top     <<<
cd: no such file or directory: tips    <<<
total 4.0K
-rw-rw-r-- 1 uranus uranus    0 Oct 13 15:02 1123.jpg
drwxr-xr-x 7 uranus uranus 4.0K Oct 20 15:34 Desktop
-rw-rw-r-- 1 uranus uranus    0 Oct 29 17:58 backup_cron.txt

Here, cmd#3 ran successfully because cmd#1 and #2 failed.


We hope this post has been useful to you.
Stay tuned for more Linux tips!