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: use |& to pipe stderr along with stdout in Bash

Bash
~/tips/tip-shell-pipe-ampersand-stderr

make 2>&1 | less

Sends both normal output and error messages through the pipe, shorter than 2>&1.

Error messages go to stderr, and a pipe only carries stdout. So the errors fly past while grep works on nothing useful.

The classic fix is 2>&1, and the order matters. Redirections are handled left to right, so cmd 2>&1 | less works, while cmd 2>&1 >file sends stderr to the terminal and only stdout to the file. Bash has a shorter form for the pipe case: |&.

make 2>&1 | less
make |& less
make 2>&1 | tee build.log

All three do the same: stdout and stderr both go into the pipe. |& is shorthand for 2>&1 |. The tee version is what I use when I want to watch a build and keep the log.

The caveat is portability. |& works in Bash 4 and newer, Zsh and Ksh, but not in plain sh or dash. The system Bash on a Mac is 3.2, where it does not exist. Also, once both streams are mixed you cannot tell them apart again, so if you need errors separately, send stderr to its own file with 2>errors.txt.

Further reading: Bash manual: Redirections, Bash manual: Pipelines, On this site: diff <(cmd1) <(cmd2) compares output without temp files, On this site: timeout stops a command that hangs

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

Link