3.2 Piping & Redirects

Authored by Atri

Piping

Piping is an advanced concept which is used for implicitly passing the output of a command or function into another command, or out to a file.

Using this can enable simple saving of command output, or the ability to chain data together.

echo "Example" \
	| tr '[:lower:]' '[:upper:]'

Redirects

This feature also exists in a different capacity when it becomes necessary to store the output of a command inside a file. When we instead want to pipe the output of a command to a file, we call this a redirect. The feature exists in a couple different capacities.

Operator Description
> Overwrite output with result
>> Append output with result
# Lets save a file using a redirect
echo This is the original content. > temp.txt
# Print the original output
cat temp.txt
# Overwrite content
echo This will replace the original content. > temp.txt
# Print again
cat temp.txt
# Append to the content
echo This will append to the previous content. >> temp.txt
# Print again
cat temp.txt

This feature can also differentiate between where to redirect depending on command exit codes. In the event you run a command which fails, this can redirect success output while all other output is sent to a different file. Bash supports 3 standard I/O streams:

Code Operator References Description
0 0> stdin Standard input stream
1 1> stdout Standard output stream
2 2> stderr Standard error stream
& &> stdout/stderr Standard output & error stream
# Success output file
echo This will pass 0> temp.txt
cat temp.txt
# Error output file
echo "Error output:"
curl fail 2> errors.txt
cat errors.txt
# Both error and success
ping example.com &> temp.txt
cat temp.txt