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: while read with < <(cmd) keeps shell variables that a pipe loses

Shell
~/tips/tip-shell-while-read-process-sub

while read -r line; do count=$((count+1)); done < <(ls /etc)

Keeps variables set in a read loop by feeding it with process substitution.

Counting lines in a loop and getting zero at the end is a classic.

count=0
while read -r line; do count=$((count+1)); done < <(ls /etc)
echo "$count"

In cmd | while read ... the loop runs in a subshell, so variables set inside are gone after done. Process substitution < <(cmd) keeps the loop in the main shell and only runs the command in the background. Note the space between the two < signs. It is a bash and zsh feature, not available in plain sh. In bash you can also use shopt -s lastpipe for scripts.

Further reading: Bash manual: Process Substitution

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link