10 Useful Chaining Operators in Linux with Practical Examples

Chaining of Linux commands means, combining several commands and make them execute based upon the behaviour of operator used in between them. Chaining of commands in Linux, is something like you are writing short shell scripts at the shell itself, and executing them from the terminal directly. Chaining makes it possible to automate the process. Moreover, an unattended machine can function in a much systematic way with the help of chaining operators.

Chaining Operators in Linux

10 Chaining Operators in Linux

Read Also: How to Use Awk and Regular Expressions to Filter Text in Files

This Article aims at throwing light on frequently used command­-chaining operators, with short descriptions and corresponding examples which surely will increase your productivity and lets you write short and meaningful codes beside reducing system load, at times.

1. Ampersand Operator (&)

The function of ‘&‘ is to make the command run in background. Just type the command followed with a white space and ‘&‘. You can execute more than one command in the background, in a single go.

Run one command in the background:

[email protected]:~$ ping ­c5 www.tecmint.com &

Run two command in background, simultaneously:

[email protected]:/home/tecmint# apt-get update & apt-get upgrade &

2. semi-colon Operator (;)

The semi-colon operator makes it possible to run, several commands in a single go and the execution of command occurs sequentially.

[email protected]:/home/tecmint# apt-get update ; apt-get upgrade ; mkdir test

The above command combination will first execute update instruction, then upgrade instruction and finally will create a ‘test‘ directory under the current working directory.

3. AND Operator (&&)

The AND Operator (&&) would execute the second command only, if the execution of first command SUCCEEDS, i.e., the exit status of the first command is 0. This command is very useful in checking the execution status of last command.

For example, I want to visit website tecmint.com using links command, in terminal but before that I need to check if the host is live or not.

[email protected]:/home/tecmint# ping -c3 www.tecmint.com && links www.tecmint.com

4. OR Operator (||)

The OR Operator (||) is much like an ‘else‘ statement in programming. The above operator allow you to execute second command only if the execution of first command fails, i.e., the exit status of first command is ‘1‘.

For example, I want to execute ‘apt-get update‘ from non-root account and if the first command fails, then the second ‘links www.tecmint.com‘ command will execute.

[email protected]:~$ apt-get update || links tecmint.com

In the above command, since the user was not allowed to update system, it means that the exit status of first command is ‘1’ and hence the last command ‘links tecmint.com‘ gets executed.

What if the first command is executed successfully, with an exit status ‘0‘? Obviously! Second command won’t execute.

[email protected]:~$ mkdir test || links tecmint.com

Here, the user creates a folder ‘test‘ in his home directory, for which user is permitted. The command executed successfully giving an exit status ‘0‘ and hence the last part of the command is not executed.

5. NOT Operator (!)

The NOT Operator (!) is much like an ‘except‘ statement. This command will execute all except the condition provided. To understand this, create a directory ‘tecmint‘ in your home directory and ‘cd‘ to it.

[email protected]:~$ mkdir tecmint 
[email protected]:~$ cd tecmint

Next, create several types of files in the folder ‘tecmint‘.

[email protected]:~/tecmint$ touch a.doc b.doc a.pdf b.pdf a.xml b.xml a.html b.html

See we’ve created all the new files within the folder ‘tecmint‘.

[email protected]:~/tecmint$ ls 

a.doc  a.html  a.pdf  a.xml  b.doc  b.html  b.pdf  b.xml

Now delete all the files except ‘html‘ file all at once, in a smart way.

[email protected]:~/tecmint$ rm -r !(*.html)

Just to verify, last execution. List all of the available files using ls command.

[email protected]:~/tecmint$ ls 

a.html  b.html

6. AND – OR operator (&& – ||)

The above operator is actually a combination of ‘AND‘ and ‘OR‘ Operator. It is much like an ‘if-else‘ statement.

For example, let’s do ping to tecmint.com, if success echo ‘Verified‘ else echo ‘Host Down‘.

[email protected]:~/tecmint$ ping -c3 www.tecmint.com && echo "Verified" || echo "Host Down"
Sample Output
PING www.tecmint.com (212.71.234.61) 56(84) bytes of data. 
64 bytes from www.tecmint.com (212.71.234.61): icmp_req=1 ttl=55 time=216 ms 
64 bytes from www.tecmint.com (212.71.234.61): icmp_req=2 ttl=55 time=224 ms 
64 bytes from www.tecmint.com (212.71.234.61): icmp_req=3 ttl=55 time=226 ms 

--- www.tecmint.com ping statistics --- 
3 packets transmitted, 3 received, 0% packet loss, time 2001ms 
rtt min/avg/max/mdev = 216.960/222.789/226.423/4.199 ms 
Verified

Now, disconnect your internet connection, and try same command again.

[email protected]:~/tecmint$ ping -c3 www.tecmint.com && echo "verified" || echo "Host Down"
Sample Output
ping: unknown host www.tecmint.com 
Host Down

7. PIPE Operator (|)

This PIPE operator is very useful where the output of first command acts as an input to the second command. For example, pipeline the output of ‘ls -l‘ to ‘less‘ and see the output of the command.

[email protected]:~$ ls -l | less

8. Command Combination Operator {}

Combine two or more commands, the second command depends upon the execution of the first command.

For example, check if a directory ‘bin‘ is available or not, and output corresponding output.

[email protected]:~$ [ -d bin ] || { echo Directory does not exist, creating directory now.; mkdir bin; } && echo Directory exists.

9. Precedence Operator ()

The Operator makes it possible to execute command in precedence order.

Command_x1 &&Command_x2 || Command_x3 && Command_x4.

In the above pseudo command, what if the Command_x1 fails? Neither of the Command_x2, Command_x3, Command_x4 would executed, for this we use Precedence Operator, as:

(Command_x1 &&Command_x2) || (Command_x3 && Command_x4)

In the above pseudo command, if Command_x1 fails, Command_x2 also fails but Still Command_x3 and Command_x4 executes depends upon exit status of Command_x3.

10. Concatenation Operator (\)

The Concatenation Operator (\) as the name specifies, is used to concatenate large commands over several lines in the shell. For example, The below command will open text file test(1).txt.

[email protected]:~/Downloads$ nano test\(1\).txt

That’s all for now. I am coming up with another interesting article very soon. Till then Stay tuned, healthy and connected to Tecmint. Don’t forget to give your Valuable feedback in our comment section.

Best Affordable Linux and WordPress Services For Your Business
Outsource Your Linux and WordPress Project and Get it Promptly Completed Remotely and Delivered Online.

If You Appreciate What We Do Here On TecMint, You Should Consider:

  1. Stay Connected to: Twitter | Facebook | Google Plus
  2. Subscribe to our email updates: Sign Up Now
  3. Get your own self-hosted blog with a Free Domain at ($3.45/month).
  4. Become a Supporter - Make a contribution via PayPal
  5. Support us by purchasing our premium books in PDF format.
  6. Support us by taking our online Linux courses

We are thankful for your never ending support.

RedHat RHCE and RHCSA Certification Book
Linux Foundation LFCS and LFCE Certification Preparation Guide

You may also like...

36 Responses

  1. anon says:

    In bash, to use rm -- !(file.txt) you may need to enable extglob:

    # type bash -O extglob
    
  2. Avinash says:

    Can anyone explain "[ -d bin ]" command, what is ''-d bin” and what "[ ]" does?

  3. firstname.lastname says:

    Something wrong in the explanation of #6 and #9.

    #6, it’s not the same as ‘if … else …’, because in command1 && command2 || command3, if command1 succeeds and command2 fails, command3 will be executed, this is not the logic with ‘if … else …’.

    #9, command1 && command2 || command3 && command4, if command1 fails, command3 will defintely be executed! You have mistakes in your statements.

  4. EBI says:

    GREAT ! APPRECIATED

  5. Naser bayat says:

    Just I want to thank all that share your experiences in the best way, it was so much useful for me.

  6. adren says:

    this article is wrong in many aspects:

    example #1 is not only bogus in many ways (you should never launch 2 commands in background that depend on each other, because the “apt-get upgrade” cannot work if the update is not finished, on top of that it is not recommended to launch in background a command that has output in the terminal)

    same logic applies with #2 (ping … &): there is no reason why one would ping a server in background (or at least do it with a quiet mode or redirecting standard output to /dev/null)

    example #3 is better, but I’m usually using the && operator (if update finishes without error, then upgrade should follow)

    as for #9, parenthesis is _NOT_ a _precedence_ operator, they are just used to run whatever commands inside in a subshell (hence, having precedence because of the priority over the rest, just like in mathematics)

    and of course, in #10 ‘\’ is not a concatenation but an escape characters (conCATenation is the ‘cat’ command, which should almost always be used with several arguments or wildcards, but shall not be used in the following form : “cat file | whatevercommand” -> see the YAUUoC syndrome)

    last warning:
    be very careful when using the extglob !(…) pattern (even more when used in a recurse deletion (rm -rf) command !!!)
    because it works perfectly when used alone (just like in the example given “rm -r !(*.html)”), but fails when one would like to use it with other arguments (so, big gotchas ahead / watch out!!!)

  7. nitpicker says:

    The example in #8 doesn’t even use the {} operator in any way, am I missing something?

  8. wildelk says:

    The example in #8 is not an example of “command combination”
    An example would be:

    [ -d bin ] || { echo Directory does not exist, creating directory now.; mkdir bin; } && echo Directory exists.

    Thanks for the article. I’ve been using Linux since 1997 and I manage 100+ linux servers in my companies datacenter. I still always find new stuff. The “command combination” was one of those.

  9. Jan Fikar says:

    There is a mistake in description of &&, should be the opposite:

    The AND Operator (&&) would execute the second command only, if the execution of first command *SUCCEEDS* , i.e., the exit status of the first command is *0*.

  10. anon says:

    The backslash \ character is not a ‘concatenation’ operator. It is a character escape operator. It prevents a following character from being interpreted as special, and instead causes it to be interpreted as itself. It’s use at the end of a line is to escape the normal meaning of the end of line character (execute command is the normal meaning) and instead to be interpreted as itself (whitespace).

Leave a Reply to Naser bayat Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.