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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
bashruns each statement in a pipe in its own subshell. (For external commands such aslsthe subshell simplyexecs 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:
EDIT: As of bash 4.2 you can use
shopt -s lastpipein 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.