A clip script counts the camera clips in a folder by piping find into a while read loop and adding one per line. The folder has six clips. The script prints 0.
#!/bin/bash
count=0
find clips -name '*.mp4' | while read -r f; do
count=$((count + 1))
done
echo "clips counted: $count"
clips counted: 0
[exit status 0]
The loop did run. Printing the counter on every pass shows it climbing to six, and then reading zero on the very next line after done:
#!/bin/bash
count=0
find clips -name '*.mp4' | sort | while read -r f; do
count=$((count + 1))
echo "inside the loop after $f: count=$count"
done
echo "after the loop: count=$count"
inside the loop after clips/clip_01.mp4: count=1
inside the loop after clips/clip_02.mp4: count=2
inside the loop after clips/clip_03.mp4: count=3
inside the loop after clips/clip_04.mp4: count=4
inside the loop after clips/clip_05.mp4: count=5
inside the loop after clips/clip_06.mp4: count=6
after the loop: count=0
[exit status 0]
Disclosure: I make an Android camera app. Nothing below uses its code or describes how it records or stores anything. The clips are files of zeros made by the setup script below, and every output is pasted from the scripts shown. Versions:
GNU bash, version 5.1.16(1)-release (aarch64-unknown-linux-gnu)
Linux 6.8.0-149-generic
find (GNU findutils) 4.8.0
#!/bin/bash
# Six stand-in clips: five small ones and one of 9 MB. Plus an empty folder.
mkdir -p clips empty
for i in 1 2 3 4 5; do head -c $((i * 1000)) /dev/zero > "clips/clip_0$i.mp4"; done
head -c 9000000 /dev/zero > clips/clip_06.mp4
The loop ran in a copy of the script
The Bash manual covers this in its section on the command execution environment: "Builtin commands that are invoked as part of a pipeline, except possibly in the last element depending on the value of the lastpipe shell option (see The Shopt Builtin), are also executed in a subshell environment." The next sentence is the one that explains the zero: "Changes made to the subshell environment cannot affect the shell’s execution environment."
The same page defines the word in one line: "A subshell is a copy of the shell process."
So while, read and the arithmetic all ran, in a copy of the shell made for that part of the pipeline. The copy counted to six and then went away. The original script saw none of it and still had the count=0 it started with.
Bash will show the copy directly. $$ keeps reporting the original script's process ID even inside a subshell, while $BASHPID reports the process actually running the line:
#!/bin/bash
echo "script: \$\$=$$ BASHPID=$BASHPID"
echo x | while read -r _; do echo "loop body: \$\$=$$ BASHPID=$BASHPID"; done
script: $$=30 BASHPID=30
loop body: $$=30 BASHPID=32
[exit status 0]
Same $$, different $BASHPID. The loop body was running in another process.
The same copy swallows exit
A counter that reads zero is easy to notice. The version of this bug that does damage is a safety check. Here the loop is meant to stop the whole upload if any clip is over 5 MB:
#!/bin/bash
# Stop the upload if any clip is larger than 5 MB.
find clips -name '*.mp4' | sort | while read -r f; do
if (( $(stat -c %s "$f") > 5000000 )); then
echo "too big: $f, stopping"
exit 1
fi
done
echo "uploading every clip"
#!/bin/bash
big=()
find clips -name '*.mp4' | while read -r f; do
(( $(stat -c %s "$f") > 4000 )) && big+=("$f")
done
echo "large clips found: ${#big[@]}"
too big: clips/clip_06.mp4, stopping
uploading every clip
[exit status 0]
large clips found: 0
[exit status 0]
The size check found the 9 MB clip and printed its warning. Then exit 1 ended the subshell, not the script, and the script carried on to the line that uploads every clip, finishing with status 0. Anything that checks that status would see success.
The second script collects the clips over 4000 bytes into an array. clip_05 and clip_06 both qualify. The array the script reads after the loop is empty, for the same reason the counter was zero.
Fix 1: feed the loop with process substitution
Putting the loop at the front and feeding it from < <(find ...) means the loop is no longer part of a pipeline. It runs in the script itself, and find is the part that runs elsewhere:
#!/bin/bash
count=0
while read -r f; do
count=$((count + 1))
done < <(find clips -name '*.mp4')
echo "clips counted: $count"
#!/bin/bash
while read -r f; do
if (( $(stat -c %s "$f") > 5000000 )); then
echo "too big: $f, stopping"
exit 1
fi
done < <(find clips -name '*.mp4' | sort)
echo "uploading every clip"
clips counted: 6
[exit status 0]
too big: clips/clip_06.mp4, stopping
[exit status 1]
The count is right, and the oversized clip now stops the script with status 1 before the upload line.
There is a cost. find now runs somewhere its exit status does not reach the script, so a typo in the folder name looks the same as an empty folder, even under set -e:
#!/bin/bash
set -e
count=0
while read -r f; do
count=$((count + 1))
done < <(find no_such_folder -name '*.mp4')
echo "clips counted: $count, script still running"
#!/bin/bash
count=0
while read -r f; do
count=$((count + 1))
done < <(find no_such_folder -name '*.mp4')
wait $!; echo "find exited $?"
echo "clips counted: $count"
find: ‘no_such_folder’: No such file or directory
clips counted: 0, script still running
[exit status 0]
find: ‘no_such_folder’: No such file or directory
find exited 1
clips counted: 0
[exit status 0]
find complained, and the script still counted 0 and kept going with status 0. In the second script wait $! straight after the loop recovered the exit status of find as 1, which the script can then act on. If the folder might not exist, check that before the loop or collect that status.
Fix 2: shopt -s lastpipe
The manual's own exception is the lastpipe option. With it set, Bash can run the last part of a pipeline in the script itself, so the original layout works:
#!/bin/bash
shopt -s lastpipe
count=0
find clips -name '*.mp4' | while read -r f; do
count=$((count + 1))
done
echo "clips counted: $count"
#!/bin/bash
shopt -s lastpipe
find clips -name '*.mp4' | sort | while read -r f; do
if (( $(stat -c %s "$f") > 5000000 )); then
echo "too big: $f, stopping"
exit 1
fi
done
echo "uploading every clip"
clips counted: 6
[exit status 0]
too big: clips/clip_06.mp4, stopping
[exit status 1]
Both behave correctly. The manual hedges with the word possibly, and two cases from my runs show why:
#!/bin/bash
set -m # job control on, as in an interactive terminal
shopt -s lastpipe
count=0
find clips -name '*.mp4' | while read -r f; do
count=$((count + 1))
done
echo "clips counted: $count"
#!/bin/bash
shopt -s lastpipe
count=0
find clips -name '*.mp4' | while read -r f; do
count=$((count + 1))
echo "$f"
done | sort > list.txt
echo "clips counted: $count, lines in list.txt: $(wc -l < list.txt)"
clips counted: 0
[exit status 0]
clips counted: 0, lines in list.txt: 6
[exit status 0]
-
Job control on, back to zero.
set -mturns on job control, as an interactive terminal has it. With that on,lastpipehad no effect and the count was 0 again. A loop that works when run as a script can still read zero when someone pastes it into a terminal to test it. -
Loop not last, back to zero. In the second script the loop's output goes on into
sort. The loop is no longer the last element, so it ran in a subshell anyway. The six lines reachedlist.txtbecause they went through the pipe; the counter did not, because it lived in the copy.
One thing lastpipe keeps that process substitution loses: find is still part of the pipeline, so pipefail sees its failure. With set -e -o pipefail, the missing folder stops the script:
#!/bin/bash
set -e -o pipefail
count=0
shopt -s lastpipe
find no_such_folder -name '*.mp4' | while read -r f; do
count=$((count + 1))
done
echo "clips counted: $count, script still running"
find: ‘no_such_folder’: No such file or directory
[exit status 1]
The script stopped at the pipeline with status 1 and did not print its last line.
Fix 3: when only exit matters, check the loop's status
If the loop only needs to stop the script and sets nothing the script reads afterwards, the subshell can stay. The status of a pipeline is the status of its last command, which here is the loop, which is whatever the subshell exited with:
#!/bin/bash
find clips -name '*.mp4' | sort | while read -r f; do
if (( $(stat -c %s "$f") > 5000000 )); then
echo "too big: $f, stopping"
exit 1
fi
done || { echo "the loop exited $?, not uploading"; exit 1; }
echo "uploading every clip"
too big: clips/clip_06.mp4, stopping
the loop exited 1, not uploading
[exit status 1]
The || { ...; exit 1; } turns the subshell's exit 1 into the script's. This does nothing for counters or arrays, which are still lost.
Watch the here-string version on an empty folder
Another common rewrite captures the list first and feeds it in with <<<. It counts six on the full folder. On an empty folder it counts one:
#!/bin/bash
count=0
list=$(find empty -name '*.mp4')
while read -r f; do
count=$((count + 1))
done <<< "$list"
echo "clips counted in an empty folder: $count"
#!/bin/bash
count=0
while read -r f; do
count=$((count + 1))
done < <(find empty -name '*.mp4')
echo "clips counted in an empty folder: $count"
clips counted in an empty folder: 1
[exit status 0]
clips counted in an empty folder: 0
[exit status 0]
$(find ...) on an empty folder is an empty string, and <<< adds a newline to what it is given, so read gets one empty line and the loop runs once with f set to nothing. The process substitution version reads no lines and counts 0. A here-string loop needs to skip lines where f is empty, or a different feed.
What to change in a script like this
- Look for any
| while readwhose loop sets a variable, adds to an array, or callsexit. Those are the ones where the change is lost. - Prefer
done < <(find ...)in scripts that run anywhere, and check separately that the folder exists, sincefindfailing there is silent. - Use
shopt -s lastpipeonly in scripts that run without job control, and only when the loop is the last part of the pipeline. Pair it withset -o pipefailto catchfindfailing. - If the loop exists only to stop the script,
done || exit 1after the pipeline is enough. - Test the empty-folder case. A here-string feed counts one there.
Things I did not test
- Other Bash versions. I ran 5.1. The quotes are from the current online manual, and what I ran matched them, but I did not run another version.
- Other shells. I did not run any shell other than Bash. Whether the last part of a pipeline runs in the current shell is one of the places shells are known to differ, so check yours rather than carrying these results over.
-
Odd filenames. The clip names here have no spaces or newlines.
read -rwith one name per line is not safe for names that contain a newline, and I did not test those here. -
Real uploads. Nothing was uploaded. The upload line is an
echo.
Sources. Quotes are from the GNU Bash Reference Manual page Command Execution Environment. Outputs are pasted unedited from the scripts above; only process IDs change between runs.
If you want an old Android phone recording in the background so there is a folder of clips for a script like this to count, the app I make is Background Camera RemoteStream on Google Play. Nothing above depends on it.
Whatever a piped loop changes stays behind in its subshell, so move the loop out of the pipeline with < <(...), or turn on lastpipe where job control is off, and try it once against a folder with no clips in it.
Top comments (0)