USD ($)
$
United States Dollar
Euro Member Countries
India Rupee
د.إ
United Arab Emirates dirham
ر.س
Saudi Arabia Riyal

Piping and Command Chaining

Lesson 4/32 | Study Time: 25 Min

Effective use of the command line in Linux often involves combining multiple commands to perform complex tasks efficiently.

Piping and command chaining are two fundamental techniques that allow users to link commands, passing outputs as inputs or executing them sequentially based on success or failure conditions.

Knowing these techniques enhances productivity, streamlines workflows, and leverages the power of the Linux shell to automate repetitive or multi-step operations. 

Piping (|): Linking Command Outputs and Inputs

Piping uses the pipe symbol | to direct the output (stdout) of one command as the input (stdin) of another. This forms a series of commands called a pipeline, where data flows through each stage sequentially.



Example:

text
ls -l | grep ".txt" | wc -l


1. ls -l lists files with details.

2. grep ".txt" filters entries containing ".txt".

3. wc -l counts the number of matched lines, effectively counting text files.


This pipeline counts how many text files are in the directory.

Command Chaining Operators: &&, ||, ;

Command chaining allows running multiple commands sequentially with control over execution flow.


1. Semicolon ;

Executes all commands one after another regardless of success or failure.

Example:

text
mkdir new_folder; cd new_folder; touch file.txt

Commands create a directory, enter it, and create a file, running each step independently.


2. Logical AND &&

Executes the next command only if the previous one succeeds (returns exit status 0).

Example:

text
gcc program.c -o program && ./program

The program runs only if compilation succeeds.


3. Logical OR ||

Executes the next command only if the previous one fails (non-zero exit status).

Example:

text
cd /invalid_directory || echo "Directory does not exist."

Echo runs only if cd fails.

Combining Command Chaining and Piping

You can combine pipes and chaining to build powerful command sequences with conditional flow.


Example:

text
ps aux | grep httpd && echo "Process found" || echo "Process not found"

This lists processes, filters for httpd. If found, it echoes "Process found"; otherwise, "Process not found".

Additional Concepts: Redirection and Background Execution


1. Output Redirection (> and >>)

Writes command output to files, overwriting or appending.

text
ls > files.txt


2. Error Redirection (2>, 2>>)

Redirects error messages.


3. Background Execution (&)

Runs commands asynchronously.

text
./long_process &

Best Practices