Redirection, pipes & the shell environment
Chain commands with pipes, redirect output and errors, and customise the environment.
By Invicly Tech, , in Linux Administration (RHCSA-style). About 10 minutes to read.
In short
Every process has three standard streams: stdin (0), stdout (1) and stderr (2). The shell can redirect them to files or connect one command's output to another's input with a pipe. Environment variables and startup files such as .bashrc shape how every command you run behaves.
Explained simply
Every program you run gets three channels for free. Standard input (stdin, number 0) is where it reads from, usually your keyboard. Standard output (stdout, number 1) is where normal results go, and standard error (stderr, number 2) is for error messages. Both outputs show up on your screen by default.
Redirection changes where those channels point. > sends output into a file, >> adds to the end of a file, and 2> catches error messages separately. A pipe, written |, connects one program's output straight into the next program's input, so small tools can work as a team.
The shell also carries settings called variables. Some are just for the shell itself; exported ones are copied to every program you start. PATH, for example, tells the shell where to look for commands, and EDITOR tells tools which editor to open.
Settings typed at the prompt vanish when you log out. To keep them, you put them in startup files such as ~/.bashrc, which bash reads every time it starts.
Press Play on a diagram to walk through it one step at a time.
- > file overwrites
- >> file appends
- 2> file captures errors
- &> file captures both
- < file feeds stdin
- 2>&1 sends errors to stdout
- << EOF starts a here-document
- /dev/null discards output
- a | b feeds a's stdout to b
- tee writes to a file and stdout
- Exit status is the last command's
- set -o pipefail catches earlier failures
- 1fd 0 stdin
Reads from the previous command's pipe
- 2fd 1 stdout
Writes into the next command's pipe
- 3fd 2 stderr
Still goes to the terminal unless redirected
- 4fd 3 and up
Files the program opens itself
In depth
What the shell does with a redirection
Redirection is done by the shell, not by the command. For cmd > out.txt, the shell starts a child process, opens out.txt (creating it or cutting it to zero length), connects that file to file descriptor 1, and only then runs cmd. The command just writes to stdout as usual and never knows a file is involved.
Two classic traps follow from this. First, sort data.txt > data.txt destroys the file: the shell empties it before sort even reads it. Write to a new file and rename it instead. Second, sudo echo text > /etc/motd fails with Permission denied, because your own shell, not root, opens /etc/motd. Use echo text | sudo tee /etc/motd > /dev/null, or tee -a to append.
- 1Shell forks a child
Still your user, still the shell
- 2Open out.txt
Created or truncated to zero right now
- 3Attach to fd 1
stdout now points at the file
- 4exec cmd
The program replaces the child
- 5cmd writes
Output lands in the file
Order matters: reading 2>&1 correctly
Redirections are applied from left to right, and 2>&1 means make fd 2 point to wherever fd 1 points right now. It copies a target; it does not create a permanent link.
In cmd > out 2>&1, stdout first goes to out, then stderr copies that, so both land in the file. In cmd 2>&1 > out, stderr first copies stdout (still the terminal), then stdout moves to the file, so errors still appear on screen. bash has a shorter form, cmd &> out, and cmd |& next pipes both streams into the next command.
Input has tricks too. A here-document (cat <<EOF) feeds several lines as stdin. Quote the marker as <<'EOF' and variables inside are not expanded, which is what you want when writing a script file. A here-string, grep x <<< "$var", feeds one string.
- Step 1: stdout goes to out
- Step 2: stderr copies stdout
- Both streams in the file
- Usually what you want
- Step 1: stderr copies the terminal
- Step 2: stdout goes to out
- Errors still on screen
- A common mistake
How pipes behave
In a | b | c, all three programs start at the same time. The kernel gives each pipe a small buffer (64 KiB by default on Linux). When it is full, the writer pauses; when it is empty, the reader waits. That is why pipelines handle files far larger than RAM.
If a reader quits early, as head does after 10 lines, the writer gets the SIGPIPE signal and stops quietly. The pipeline's exit status is that of the last command only, so a failing first command is invisible. In scripts use set -o pipefail, or check the PIPESTATUS array, which holds every command's status.
Each part of a pipeline runs in a subshell. So echo hi | read x leaves x empty in your shell. Use x=$(echo hi) instead.
- echo "${PIPESTATUS[@]}" shows every exit code of the last pipeline
- tee -a appends instead of overwriting
- xargs turns lines of input into command arguments
Variables, export and the environment
NAME=value creates a shell variable. It exists only in the current shell. export NAME copies it into the environment, the list of settings each child process inherits. A child can never change its parent's variables, which is why a script that sets PATH does not affect your prompt unless you source it.
You can set a variable for one command only: LANG=C sort file. env and printenv list the environment; set lists shell variables too. Always use double quotes: "$FILE" keeps a name with spaces as one word, while single quotes stop expansion completely, so '$HOME' stays literally $HOME. Command substitution, $(cmd), puts a command's output into a line; it nests cleanly, unlike the older backtick form.
- PATH is searched left to right; the first match wins
- unset NAME removes a variable
- echo $? prints the last command's exit status
Which startup file runs when
bash reads different files depending on how it starts. A login shell, such as an SSH session or a console login, reads /etc/profile (which also runs every .sh script in /etc/profile.d/), then the first one it finds of ~/.bash_profile, ~/.bash_login and ~/.profile. An interactive non-login shell, such as a new terminal tab, reads ~/.bashrc. Both RHEL and Ubuntu make the login files source ~/.bashrc too, so in practice ~/.bashrc is the place for aliases, functions and your prompt.
For settings every user should get, add a file such as /etc/profile.d/proxy.sh rather than editing /etc/profile, so package updates do not overwrite it. After editing, run source ~/.bashrc (or open a new shell) to apply the change. Scripts run with bash script.sh are non-interactive and read none of these files.
Learn it in 5 short steps
About 30m each. Track them with a timer in your plan.
- 1Redirect stdout and stderr to files~30m
- 2Chain commands with pipes and tee~30m
- 3Set variables and export them~30m
- 4Persist settings in .bashrc~30m
- 5Use command substitution~30m
Key points
- Order matters: cmd > out 2>&1 captures both, cmd 2>&1 > out does not.
- export makes a variable visible to child processes.
- Put personal aliases and variables in ~/.bashrc; system-wide ones in /etc/profile.d.
- $(command) substitutes a command's output into another command.
Key terms
Tap a card to flip it. 0/5 known
Examples
find / -name "*.conf" 2>/dev/null > confs.txt
dnf list installed | tee installed.txt | wc -l
echo "export EDITOR=vim" >> ~/.bashrc && source ~/.bashrc
echo "Kernel: $(uname -r), uptime: $(uptime -p)"
cat > /tmp/motd <<EOF
Authorised use only
EOFDiscard errors, save and count, persist a variable, use substitution and a here-doc.
Log a long job and still watch it
You run a backup script that takes an hour. You want all its output, errors included, in a dated log file, and you also want to see progress on screen. Step 1: merge stderr into stdout with 2>&1. Step 2: pipe into tee, which writes to the file and to the screen. Step 3: turn on pipefail so the line fails if the script fails, not just if tee fails. Step 4: check the exit status.
set -o pipefail
LOG=~/backup-$(date +%F).log
./backup.sh 2>&1 | tee "$LOG"
echo "exit status: $?"
grep -i error "$LOG"Write a root-owned config file from a normal shell
You need to create /etc/profile.d/editor.sh so every user gets vim as their editor. sudo cat > file does not work, because your own shell opens the file. Step 1: send a quoted here-document into sudo tee, which runs as root and opens the file itself. The quoted 'EOF' stops your shell from expanding anything inside. Step 2: hide tee's screen copy with > /dev/null. Step 3: open a new login shell and confirm the variable is set.
sudo tee /etc/profile.d/editor.sh > /dev/null <<'EOF'
export EDITOR=vim
export VISUAL=vim
EOF
ls -l /etc/profile.d/editor.sh
bash -lc 'echo $EDITOR' # vimQuick reference
- cmd > out 2>&1 or cmd &> out captures stdout and stderr in one file
- cmd 2>/dev/null hides errors; cmd > /dev/null 2>&1 hides everything
- echo text | sudo tee -a /etc/file appends to a root-owned file
- set -o pipefail makes a pipeline fail if any command in it fails
- VAR=value cmd sets a variable for that one command only
- Quoted <<'EOF' keeps $ signs literal inside a here-document
- Put aliases in ~/.bashrc and system-wide settings in /etc/profile.d/NAME.sh
- source ~/.bashrc applies changes to the current shell
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Run find / -name '*.repo' as a normal user. Save the results in repos.txt and the Permission denied errors in errors.txt, then count the lines in each.
- Exercise 2medium
Add a permanent alias ll='ls -lah' and a variable BACKUP_DIR=/srv/backup that child processes can see. Prove both work in a new shell.
- Exercise 3hard
Write a one-liner that prints the exit status of every command in the pipeline grep root /etc/shadow | wc -l when run as a normal user, then explain the numbers.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between > and >>?
- > empties the file and writes fresh content. >> keeps what is there and adds to the end.
- What is /dev/null?
- A special file that throws away everything written to it and returns nothing when read. Redirect output there when you do not need it.
- Should I put settings in .bashrc or .bash_profile?
- Put almost everything in ~/.bashrc. On RHEL and Ubuntu the login files already source it, so it applies to SSH logins and new terminals alike.
- Why does my variable disappear after the script ends?
- A script runs in a child process, and children cannot change the parent's variables. Run it with source script.sh to apply its variables to your current shell.