Home

7 Handy Linux Shell Operators

Chaining commands in Linux means stringing several together so they run in a sequence — and the operator between them decides exactly how they run. It's basically the smallest version of writing a shell script.

1. Ampersand (&)

& runs a command in the background. Just put a space and & after the command. You can stack multiple in the background at once.

bash
apt update &

Two commands in the background at the same time:

bash
apt-get update & apt-get upgrade -y &

2. Semicolon (;)

The semicolon lets you run several commands sequentially in a single line — each one runs after the previous finishes, regardless of success.

The example below first updates the package list, then upgrades the installed packages.

bash
apt-get update ; apt-get upgrade ;

3. AND operator (&&)

&& runs the next command only if the previous one succeeded (exit code 0). Useful for guarding follow-up steps on the success of the previous one.

Below, we ping linuxpedi.com and only print "Linuxpedi Site UP" if the ping succeeds. If the ping fails, the echo never runs.

bash
ping -c 4 linuxpedi.com && echo 'Linuxpedi Site UP'

4. OR operator (||)

|| is essentially the shell's else. The second command runs only if the first one failed (exit code != 0).

Below, rm would refuse to delete a directory without -r, so the second branch fires with the friendly reminder.

bash
rm snap || echo 'You need -r to remove a directory'

5. AND–OR combined (&& and ||)

Combining && and || gives you a one-liner if/else.

Below, we ping linuxpedi.com 4 times. If pings come back, print "Site UP"; otherwise "Site Down".

bash
ping -c4 linuxpedi.com && echo "Site UP" || echo "Site Down"
bash
root@linuxpedi:~# ping -c3 linuxpedi.com && echo "Site UP" || echo "Site Down"PING linuxpedi.com (34.141.144.143) 56(84) bytes of data.64 bytes from 143.144.141.34.bc.googleusercontent.com (34.141.144.143): icmp_seq=1 ttl=61 time=0.936 ms64 bytes from 143.144.141.34.bc.googleusercontent.com (34.141.144.143): icmp_seq=2 ttl=61 time=0.365 ms64 bytes from 143.144.141.34.bc.googleusercontent.com (34.141.144.143): icmp_seq=3 ttl=61 time=0.384 ms--- linuxpedi.com ping statistics ---3 packets transmitted, 3 received, 0% packet loss, time 2010msrtt min/avg/max/mdev = 0.365/0.561/0.936/0.264 msSite UP

6. Pipe (|)

The pipe sends the stdout of the first command into the stdin of the second. Classic example: list a directory and count the entries.

bash
ls /root | wc -l
bash
root@linuxpedi:~# ls /root | wc -l2