Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

There are 2 pieces of code here, and the value in $1 is the name of a file which contains 3 lines of text.

Now, I have a problem. In the first piece of the code, I can't get the "right" value out of the loop, but in the second piece of the code, I can get the right result. I don't know why.

How can I make the first piece of the code get the right result?

#!/bin/bash

count=0
cat "$1" | while read line
do
    count=$[ $count + 1 ]
done
echo "$count line(s) in all."

#-----------------------------------------

count2=0
for var in a b c
do
    count2=$[ $count2 + 1 ]
done
echo "$count2 line(s) in all."
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.9k views
Welcome To Ask or Share your Answers For Others

1 Answer

This happens because of the pipe before the while loop. It creates a sub-shell, and thus the changes in the variables are not passed to the main script. To overcome this, use process substitution instead:

while read -r line
do
    # do some stuff
done < <( some commad)

In version 4.2 or later, you can also set the lastpipe option, and the last command in the pipeline will run in the current shell, not a subshell.

shopt -s lastpipe
some command | while read -r line; do
  # do some stuff
done

In this case, since you are just using the contents of the file, you can use input redirection:

while read -r line
do
    # do some stuff
done < "$file"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...