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: shopt -s lastpipe keeps variables set inside a piped while loop

Shell
~/tips/tip-shell-lastpipe-while-read-variable

shopt -s lastpipe

Runs the last command of a pipeline in the current shell so its variables survive.

This one trips up a lot of bash scripts. You count lines in a while read loop that sits at the end of a pipe, and afterwards the counter is back at zero.

Each part of a pipeline normally runs in a subshell, so a variable set in the loop disappears with it. The lastpipe shell option changes that. The manual says that when job control is not active, bash runs the last command of a pipeline in the current shell environment:

#!/usr/bin/env bash
shopt -s lastpipe
count=0
printf '%s
' one two | while read -r line; do count=$((count+1)); done
echo "$count"   # 2

Without the shopt line the script prints 0, because the loop ran in a subshell and its copy of count was thrown away. I checked this on bash 5.2 and it behaves as the docs describe.

The condition about job control matters. A script has job control off, so it works there. In an interactive terminal job control is on, so lastpipe does nothing and you would see 0 again.

If you want something that works in both places, read from a process substitution instead, so the loop is not part of a pipeline at all:

count=0
while read -r line; do count=$((count+1)); done < <(printf '%s
' one two)
echo "$count"   # 2

The input then runs in the subshell and the loop stays in your shell. That form needs bash too, but it does not depend on a shell option, which makes it the safer choice for a script someone else might source.

Further reading: bash(1) manual page

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