Previous Page
PCLinuxOS Magazine
Article List
Next Page

Running Multiple Commands From The Command Line Or A Bash Script

by Paul Arnote (parnote)

There may be times, when you are working in a terminal session or writing a bash script that you want to execute multiple commands. Fortunately, and as you might expect, Linux gives us multiple ways to do this.

command1; command2; command3

When separated by a semicolon, all of your commands will be executed, regardless if they return an error code or not. This situation will probably satisfy a lot of your needs. In the illustrative image above, I've executed the ls command (to list the directory conents of my /home directory), followed by the cal command (to display a calendar of the current month), and then "pinged" three times with the ping command. Each were separated by a semicolon, and each executed in the order listed. While it may not be a very practical example, it does illustrate the concept fairly well.

But, what if you wanted the subsequent commands to be executed only if the previous command successfully completed, without an error code (other than zero)? Linux has us covered for that eventuality.

command1 && command2 && command3

Using a && (two ampersands) to separate your commands will allow the second command to execute only if the first command successfully completes without an error, and the third command to execute only if the second command successfully completes without an error.

Taking a slightly different path, we can also "chain" commands together to execute only if the previous command failed or returned an error code (other than zero). Instead of using the &&, we use two pipe characters (||), which is the same as saying "or." While this can be a bit complex to wrap your mind around, I'll try to explain.

command1 || command2 || command3

With this syntax, if the first command returns an error code, then and only then will the second command be executed. If the first command and second command return an error, then and only then will the third command be executed. If the first command successfully completes, then neither the second or third commands will be executed. If the first command is unsuccessful but the second command successfully completes, then the third command will be ignored.


Many Linux users may find little need to use the command line, thanks to the fantastically complete GUI desktops we have to choose from. Other Linux users may be afraid of the command line. But sometimes, there are things you can only do from the command line. Yet other times, using the command line is the fastest way to get things done. Every Linux user owes it to themselves to at least learn their way around the command line. You never know when you might find it helpful and useful.

Previous Page              Top              Next Page
Copyright (c) 2013, The PCLinuxOS Magazine. All Rights Reserved.