sof
sof

Reputation: 9649

variable reset in a bash script

a simple variable test:

#!/bin/bash

N=0

ls -l | while read L; do
 N=$((N+1))
 echo $N
done

echo "total $N"

ran it then output:

1
2
3

total 0

i expected final N=3: "total 3", but why did the value reset to 0 after the loop?

Upvotes: 3

Views: 11948

Answers (1)

Neil
Neil

Reputation: 55392

bash runs each statement in a pipe in its own subshell. (For external commands such as ls the subshell simply execs the command.) This effectively makes all of the variables local. You generally have to work around this by using redirection or command substitution instead of a pipe.

EDIT: This seems to work:

#!/bin/bash
IFS=
N=0

while read L; do
  N=$((N+1))
  echo $N
done <<<$(ls -l)

echo "total $N"

EDIT: As of bash 4.2 you can use shopt -s lastpipe in your script to disable the subshell for the last command in a pipe, which would then allow the rest of the original code to work as desired.

Upvotes: 8

Related Questions