I have a code snippet, as follows.
#!/bin/bash
filename="tmp_list_filenames"
line_index=0
cat $filename | while read processed_data_filename; do
line_index=$(($line_index + 1))
var="haha$line_index"
done
echo "thevar:$var"
The output is simply thevar:, or $var is not raechable outside while loop. Why is it the case here? I also tried replace while codeline with while [ $line_index -lt 3 ]; do, as follows,
#!/bin/bash
filename="tmp_list_filenames"
line_index=0
while [ $line_index -lt 3 ]; do
line_index=$(($line_index + 1))
var="haha$line_index"
done
echo "thevar:$var"
Then, it prints thevar:haha4. It is very strange to me, can anyone explain this?
Classic example of UUOC. By putting the while loop in a pipeline, it is running in a subprocess. There is no need for the pipe:
should solve the problem