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

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

bash - assign a value to a variable in a loop

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...