Linux Format

Chain operators...............

Nick Peers reveals how to group multiple commands together with the help of chaining operators – no heavy machinery involved.

-

Nick Peers groups multiple commands together by using chaining operators.

The art of command chaining is simple: multiple Linux commands are combined into a single line. The obvious use for a chain is to run multiple commands one after the other, enabling you to leave a lengthy process to its own devices without having to intervene. For example, quickly check for updates and install them using the following chained command: $ sudo apt-get update && sudo apt-get upgrade

The && that separates the two commands is known as an operator, and Linux provides you with a choice of different operators, enabling you to control how each command in the chain behaves based on the previous command.

In this month’s guide to the command line, we’re going to show how to use the most commonly used operators.

Sequential operators

Let’s start with the semi-colon (;) operator. Use this to split commands on a single line and they’ll run in sequential order, one after the other: $ sudo apt-get update ; sudo apt-get upgrade

There’s no apparent limit to how many commands you can queue up in this way. The semi-colon operator will run each command regardless of what happens to the previous command, which isn’t always desirable. In the above example, we normally only want sudo apt-get upgrade to run if the sudo apt-get update command completes successful­ly.

This is where the && operator comes in, which is used in place of the ; operator. The && operator is also known as the AND operator. This means that the second (and subsequent) commands will only run if the preceding command(s) are successful: $ sudo apt-get update && sudo apt-get install appname && appname

So, in our example above, appname will only run if it’s been installed, and it will only install if sudo apt-get update runs. That means if you were to be told that the update command is being used by another process then the app installati­on and any subsequent commands would be cancelled.

The example below pings a remote machine before attempting to connect to it. If the ping fails, ssh isn’t invoked: $ ping -c1 192.168.0.3 && ssh user@192.168.0.3

If you want a command to execute only if the first command fails, use the II (OR) operator. It instructs the second command to run only if the first command returns an exit status of 1 or higher (failure) rather than 0 (success): $ apt-get update || echo You forgot to use sudo

You can, of course, combine && and II . It’s like producing an IF… ELSE… statement when programmin­g: $ apt-get update && sudo apt-get upgrade || echo Oops, you forgot sudo!

Should you need to produce more complex combinatio­ns of commands, you’ll want to make use of the command

combinatio­n operator. This enables you to group related commands with each other inside {} characters, thus effectivel­y treating them as their own separate command within the context of other commands.

The following example will first check for the existence of a file called linux.txt. If the file exists, the first echo command is processed; if not, the commands inside the {} operators will be executed one after the other instead: $ test -f ~/Documents/linux.txt && echo linux.txt exists! || { echo linux.txt doesn’t exist – creating now.; touch ~/ Documents/linux.txt; }

Leave a space between { and the command, and make sure you include a trailing ; at the end of the command to return to the shell after the final command is executed.

Order is everything

It can be confusing working out the order in which to chain commands together. Left-most operations are executed first regardless of the operator. Because && and II have the same precedence, whichever comes first is executed first.

Take this example: $ true || echo aaa && echo bbb

As things stand, the first statement executes. Because it’s true , you might expect the second and third commands to be ignored. In fact, only the first echo command is ignored, so bbb is still printed. To get around this, you need to use brackets to enclose commands you want to group together: $ true || ( echo aaa && echo bbb )

Here’s a real-world practical example: $ ( sudo apt-get update && sudo apt-get upgrade ) || echo Update failed.

This ensures the Update failed. message will be displayed if either command fails, not simply the apt-get upgrade one.

If using operators becomes confusing, you can make use of Bash’s own IF , THEN and ELSE commands if you prefer. These commands need to be concluded with fi : $ if ls *.txt ; then echo We’ve found text files ; else echo Nope, no text files here! ; fi

These commands work best with simple conditiona­l statements like that above.

Run processes in parallel

All the operators we’ve looked at so far run commands in series – in other words, one followed by the next. This ties up the Terminal, forcing you to wait until the command completes before you can move on to the next one. In some cases, you might like to be able to run commands in a multitaski­ng environmen­t – in other words, in parallel. You could open another Terminal window if you’re at the desktop, or you could make use of the & operator, which instructs the command, script or process to run in the background, freeing up the command line for other tasks. To do this, add the & operator to the end of your command, like so: $ sudo apt-get upgrade & The command will output something like: [1] 3215

The number indicates the Process ID allocated to the command, which is now running in the background, freeing up the Terminal for use for other commands. Again, the & character can be used to run subsequent commands in parallel if required. Monitor your process with this command: $ ps -f p 3215

Substitute 3215 with your command’s Process ID. When you hit Enter you should see a status update. Done indicates it’s successful, while Stopped usually means it’s failed. While the process runs, you can get on with other commands.

Not only can you run single commands in parallel this way, you can chain multiple commands on the same line together too, all of which will run simultaneo­usly in the background: $ ping -c1 google.com & ping -c1 linuxforma­t.co.uk &

Here, output from both commands will be mixed on-screen as they’re performed in parallel. Exercise caution when deciding which commands to run in parallel. There’s no point performing sudo apt-get update and sudo apt-get upgrade in parallel, because the latter command relies on the former to complete before it can function. So if the command or tool you want to run isn’t designed to be executed in the background, think long and hard about doing so.

 ??  ?? The && operator ensures subsequent commands will only run if the preceding command is successful.
The && operator ensures subsequent commands will only run if the preceding command is successful.
 ??  ?? Nick Peers has been playing around with computers for over 30 years, and has been dabbling with Linux for the best part of a decade.
Nick Peers has been playing around with computers for over 30 years, and has been dabbling with Linux for the best part of a decade.
 ??  ?? You can build complex strings of commands that rely on certain criteria in order to act in a certain way.
You can build complex strings of commands that rely on certain criteria in order to act in a certain way.

Newspapers in English

Newspapers from Australia