Saltar al contenido ForoHackers

Bash while read loop counts 2 inside, 0 afterwards

DepuraciónLinuxScripts de shell
#7017 · · Citar · Denunciar

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 · · Citar · Denunciar

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

#7198 · · Citar · Denunciar

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 · · Citar · Denunciar

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 · · Citar · Denunciar

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 · · Citar · Denunciar

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 · · Citar · Denunciar

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

No has iniciado sesión, así que esto se publica como anónimo: no se guarda con ello ninguna cuenta, nombre ni dirección, y no puede llevar enlaces ni imágenes. Inicia sesión o únete para publicar con tu nombre. Los registros de nuestro servidor web guardan la dirección y la hora de cada petición hasta 14 días; para que la tuya no quede en ellos, usa Tor. Para escribir al equipo de forma confidencial, usa el buzón. Firmar como fuente habitual (una clave guardada solo en este navegador)

Enviar tarda unos segundos aquí: tu navegador resuelve antes una prueba de trabajo contra el spam.

Responder