brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: in bash, 2>&1 only follows where stdout points at that moment

Bash
~/tips/tip-shell-redirection-order-2-1-matters

cmd > file 2>&1

Explains why `cmd > file 2>&1` and `cmd 2>&1 > file` send errors to different places.

Redirections look like they are order-free, and they are not. The two spellings below get used as if they were the same thing, and they do different jobs.

cmd > file 2>&1

The shell reads redirections left to right. 2>&1 means “make file descriptor 2 point to wherever descriptor 1 points right now”. After > file, descriptor 1 points at the file, so errors go there too. With the order swapped, descriptor 2 is copied while stdout still points at the terminal, and only then does stdout move to the file.

A small function that writes one line to each stream shows it:

f() { echo out; echo err >&2; }
f > A.txt 2>&1
cat A.txt
out
err
f 2>&1 > B.txt
err
cat B.txt
out

With the second order, err still shows up on the terminal and only out ends up in B.txt.

That is not always a mistake. 2>&1 >/dev/null in front of a pipe sends only the errors down the pipe and throws the normal output away. f 2>&1 >/dev/null | tr a-z A-Z prints ERR, and nothing else.

Bash also has the short form &> file, which sends both streams to the file. With f &> D.txt, both out and err end up in D.txt. In scripts I’d keep the long form > file 2>&1, because it says exactly what happens.

Further reading: Bash reference manual

More Bash tips echo {01..10} export HISTIGNORE='ls*:pwd:cd*' #rsync -av --delete /srv/media/ /mnt/backup/media/ APP_HOST=example.com set -e All Bash tips (52) All topics

Link