Skip to the content ForoHackers
Log inJoin

Bash while read loop counts 2 inside, 0 afterwards

DebuggingLinuxShell scripting
#7017 · · Quote · Report

shift note → new complaint bucket. file named gripes, two lines, "radio" and "smell behind fridge". this runs in bash on the shop laptop.

n=0
cat gripes | while IFS= read -r line; do
    n=$((n + 1))
    echo "inside $n"
done
echo "outside $n"

inside 1, inside 2, outside 0. wasn't expecting to love the bucket this much. is the last line somehow happening first?

#7195 · · Quote · Report

rename n to smellBehindFridgeCount. no difference but now you can make your successor type that when they quit

#7198 · · Quote · Report

the order's fine. on a default Bash that while loop is on the right of a pipe and runs in another shell process. it gets your zero, counts to two, exits. you're back in the process that still has its zero. give the file directly to the loop. same two lines, same read.

n=0
while IFS= read -r line; do
    n=$((n + 1))
done < gripes
echo "$n"
#7207 · · Quote · Report

got 2. put an echo just after done again this morning in case it was a night thing. still 2. ty for letting me have that one

#7213 · · Quote · Report

czyli dziecko dostaje dwie skargi, wychodzi i rodzic spokojnie idzie spać. świetny system. mój właściciel mieszkania też chyba działa w bashu

#7218 · · Quote · Report

before somebody turns up here with a Bash manual and demands my apron: Bash has a lastpipe option that can run the last part in the current shell when job control is off. that's how somebody can honestly paste the first version and swear it prints 2. the version you took to work doesn't depend on that switch.

#7237 · · Quote · Report

somebody wrote "the bucket" inside the bucket. we have recursion now too

You are not logged in, so this goes up anonymously: no account, no name and no address is stored with it, and it may carry no link and no image. Log in or join to post under your name. Our web server's logs keep the address and time of every request for up to 14 days; to keep yours out of them, use Tor. To reach the staff in confidence, use the drop. Sign as a returning source (a key kept only in this browser)

Sending takes a few seconds here: your browser first works out a proof of work against spam.

Reply