How to Use Double and Single Pipes in Bash

MD Aminul Islam Feb 02, 2024
  1. Use the Double Pipe || in Bash
  2. Use the Single Pipe | in Bash
How to Use Double and Single Pipes in Bash

In Bash, the double pipe || is also known as the OR operator like in other programming languages. On the other hand, the single pipe | is known as the pipe.

In this article, we will see how to use the double pipe, also known as OR, and the pipe in Bash script. Also, we will see necessary examples and explanations to make the topic easier.

Use the Double Pipe || in Bash

Putting this double pipe || between two commands will try to run the first command. If running the first command is unsuccessful, it will go for the second one.

Please note that if the first command runs successfully, it won’t run the second one.

The general syntax of the double pipe is:

<COMMAND_1> || <COMMAND_2>

In the example shared below, we put two commands together with an OR operator. The code for our example is something like the one below:

ls -l || echo "This is a text"

The output of the example shared below shows that it only executed the first command. The output of the above example is something like the following:

total 12
-rwxrwxrwx 1 author author   99 Aug  4 14:45 1_Test.txt
-rwxrwxrwx 1 author author  204 Jul 19 15:04 BatchCode.bat
-rwxrwxrwx 1 author author  159 Aug  5 23:04 example.sh
-rwxrwxrwx 1 author author   32 Jul 12 14:05 file1.bat
-rwxrwxrwx 1 author author   33 Jul 12 14:05 file2.bat
-rwxrwxrwx 1 author author   32 Jul 12 14:05 file3.bat
-rwxrwxrwx 1 author author 1330 May 25 00:54 sample.vbs

Use the Single Pipe | in Bash

This | is also known as the pipe in Bash. It is used when the output of the first command works as an input of the second command.

The general syntax of the pipe is:

<COMMAND_1> | <COMMAND_2>

Let’s go through the below example. Suppose we have a Bash script with the following content:

echo "This is the text from the Bash script"

Our example below will run the Bash script shared above with an external command. The whole command will look like the following:

echo "This is a command" | ./example.sh

Now, after running the above command, you will get the output below:

This is the text from the Bash script

Please note that all codes used in this article are written in Bash. It will only be runnable in the Linux Shell environment.

MD Aminul Islam avatar MD Aminul Islam avatar

Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.

LinkedIn

Related Article - Bash Operator