Chaining of Linux commands means, combining several commands and making them execute based upon the behavior of the 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 systematically with the help of chaining operators.
This article aims to shed light on frequently used command-chaining operators. It provides short descriptions and corresponding examples that can enhance your productivity and enable you to write concise, meaningful code while reducing system load at times.
1. Ampersand Operator (&) – Run Linux Command in Background
The function of ‘&‘ is to make the command run in the background. Just type the command followed by a white space and ‘&‘. You can execute more than one command in the background, in a single go.
Run a single Linux command called ‘ping‘ in the background:
ping -c5 www.tecmint.com &
Run two or multiple apt commands in the background, simultaneously:
apt update & apt upgrade &
2. Semi-Colon Operator (;) – Run Multiple Commands
The semi-colon (;)
operator makes it possible to run, several commands in a single go and the execution of the command occurs sequentially.
apt update ; apt upgrade ; mkdir test
The above command combination will first execute the update instruction, then the upgrade instruction, and finally will create a ‘test’ directory under the current working directory.
3. AND Operator (&&) – Run Second Command Upon Success
The AND Operator (&&) would execute the second command only, if the execution of the 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 the last command.
For example, I want to visit the website tecmint.com using the links command, in the terminal but before that, I need to check if the host is live or not.
ping -c3 www.tecmint.com && links www.tecmint.com
4. OR Operator (||) – Conditional Command Execution
The OR Operator (||) is much like an ‘else‘ statement in programming. The ||
operator allows you to execute the second command only if the execution of the first command fails, i.e., the exit status of the first command is ‘1‘.
For example, I want to execute ‘apt update‘ from a non-root account and if the first command fails, then the second ‘links www.tecmint.com‘ command will execute.
apt update || links tecmint.com
In the above command, since the user was not allowed to update the system, it means that the exit status of the 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! The second command won’t execute.
mkdir test || links tecmint.com
Here, the user creates a folder ‘test‘ in his home directory, for which the 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 (!) – Selective Execution of Commands
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.
mkdir tecmint cd tecmint
Next, create several types of files in the folder ‘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‘.
ls a.doc a.html a.pdf a.xml b.doc b.html b.pdf b.xml
Now delete all the files except the ‘html‘ file all at once, in a smart way using the rm command.
rm -r !(*.html)
Just to verify, last execution. List all of the available files using ls command.
ls a.html b.html
6. AND – OR operator (&& – ||) – Conditional Execution of Commands
The above operator is a combination of ‘AND‘ and ‘OR‘ Operator. It is much like an ‘if-else‘ statement.
For example, let’s do a ping to tecmint.com, if success echo ‘Verified‘ else echo ‘Host Down‘.
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 the same command again.
ping -c3 www.tecmint.com && echo "verified" || echo "Host Down"
Sample Output:
ping: unknown host www.tecmint.com Host Down
7. PIPE Operator (|) – Streamlined Output Processing
This PIPE operator is very useful where the output of the 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.
ls -l | less drwx------ tecmint tecmint 4.0 KB Thu Nov 16 12:03:02 2023 AnyDesk drwxrwxr-x tecmint tecmint 4.0 KB Tue Oct 10 10:44:35 2023 bin drwxr-xr-x root root 4.0 KB Wed Nov 24 22:05:09 2021 DEBIAN drwxrwxr-x tecmint tecmint 4.0 KB Sat Nov 18 12:32:49 2023 Desktop drwx--x---+ tecmint tecmint 100 KB Fri Dec 8 12:00:49 2023 Downloads drwxrwxr-x tecmint tecmint 4.0 KB Wed Sep 13 10:25:07 2023 llpp drwxrwxr-x tecmint tecmint 4.0 KB Thu Nov 16 14:26:46 2023 MyImages drwxrwxr-x tecmint tecmint 4.0 KB Wed Sep 13 14:55:42 2023 Obsidian Vault drwxrwxr-x tecmint tecmint 4.0 KB Tue Oct 10 10:44:32 2023 opt drwxrwxr-x tecmint tecmint 4.0 KB Thu Nov 16 14:46:54 2023 php drwxrwxr-x tecmint tecmint 4.0 KB Thu Nov 16 15:54:33 2023 tar_examples .rw-rw-r-- tecmint tecmint 73 KB Mon Sep 18 11:46:02 2023 Apache-Web-Server-Security.png .rw-rw-r-- tecmint tecmint 2.2 KB Sun Oct 29 00:17:15 2023 ChatGPT-SEO-Prompts .rw-rw-r-- tecmint tecmint 41 KB Thu Nov 23 11:34:33 2023 Create-Users-in-Linux.png ...
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 the corresponding output.
[ -d bin ] || { echo Directory does not exist, creating directory now.; mkdir bin; } && echo Directory exists.
9. Precedence Operator () – Managing Command Execution Order
The ()
operator makes it possible to execute commands 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 execute depending upon the exit status of Command_x3.
10. Concatenation Operator (\) – Multiline Command Concatenation
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 a text file test(1).txt.
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.
10. Example is showing escape characters, not concatenation. The operator has two functions, escape and concatenate.
Concatenation example:
The above outputs the line split by a \n or new line escape character:
Thanks, very useful and enlightening examples…
Hey there,
Nice article, thank you.
I got one question. As I understand it, the following statement, within the example for the precedence operator, is false:
“In the above pseudo command, what if the Command_x1 fails? Neither of the Command_x2, Command_x3, Command_x4 would be executed, for this, we use Precedence Operator, as:”
As is command_x1 fails, command_x2 will not be executed but Command_x3 will, and the execution of Command_x4 will depend on the result of Command_x3.
Cheers
Hauke
As per your example, NOT operator is not working you gave
rm -r !(*.html)
.bash: !: event not found
[root@localhost tecmint]# rm -r !(*.html)
bash: !: event not found
In bash, to use
rm -- !(file.txt)
you may need to enable extglob:Can anyone explain
"[ -d bin ]"
command, what is''-d
bin” and what"[ ]"
does?[ -d bin ]
in bash is equivalent to'test - bin'
it tests if bin is a directory.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.
GREAT ! APPRECIATED
Just I want to thank all that share your experiences in the best way, it was so much useful for me.
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!!!)
The example in #8 doesn’t even use the {} operator in any way, am I missing something?
@Nitpicker,
No you’re right, We’ve corrected the command as per example suggested by @wildelk
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.
@Wildelk,
Thanks for the example, I’ve added to the list as example #8..
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*.
@Jan,
Thanks for the pointing out, yes that was a mistake and corrected in the writeup as per your findings…:)
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).
Awesome article. I use pipe and AND operators in class subjects and now i feel like introducing all of them to my class.
Thank you.
@Minhaj,
I am glad, that you liked this article..
“`
&& and || are (were?) backwards. Try the following:
false || echo hi
true && echo hi
false -> 1 (failure) and true -> 0 (success)
“`
there are mistakes to be corrected:
AND Operator (&&)
if the execution of first command SUCCEEDS
OR Operator (||)
the exit status of first command is ””’0””’
Excellent !! keep it up..
Good to know these operators. I only use very few of them on daily basis. Need to start using all of ’em so that I don’t forget their usage.
Thanks for sharing.
The example in 8 uses the “test” operator. See man test or man [ (yes open bracket) for more info. Curlies (ie. parenthesis or braces) are used to disambiguate variables. For example, if I do MYUSER=’root’, then “${MYUSER}rules” is “root-isgreat”, but $MYUSERrules is undefined. You can also use curlies for precedence (ie. running several commands before doing something else).
These mistakes happens when you do copy paste :-)
Example 1: Run two command in background, simultaneously:
i don’t think the command “apt-get update & apt-get upgrade &” will run simultaneously because the first apt-get will create a lock and second apt-get will have to wait for the lock release. so in this particular example they will run sequentially rather than simultaneously.
Example 8 uses one operator in the title and another in the script. I think the title is wrong
This article looks like it’s a slightly rehashed version of this one:
http://www.linuxnix.com/2012/07/23-awesome-less-known-linuxunix-command-chaining-examples.html
See example 24 on that page to find out what Example 8 above is missing.
Also, in Example 10, ‘\’ is used as escape character, because ‘(‘ and ‘)’ won’t be recognized by shell as literal characters. A correct example for this section would be as follows:
$ nano \
teste.txt
or
$ nano teste\
.txt
Great article.
correction about: 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.
Example in 10 doesn’t concatenate lines but escapes character, so it doesn’t make much sense with explanation given.
it seems example 10 is also missing…
( echo -n ‘Good writing man!, ‘ || echo ‘I hate it’ ) && echo ‘I love this’
in example 10, the “\” is actually used for escaping ,not for concatenation.
Good Tutorial
Very very good, greetings from Costa Rica. Excellent site!
Example 8 seems missing something!!
a mistake in definition of && operator: “The AND Operator (&&) would execute the second command only, if the execution of first command fails”
definition for && is wrong !