The while LOOP trap and shellwhile trap in shell
When writing A while LOOP, I found a problem. In the while LOOP, I assigned values to variables, Defined variables, array definitions, and other environments, and the environment became invalid outside the loop.
A simple test script is as follows:
#!/bin/bashecho "abc xyz" | while read linedo new_var=$linedoneecho new_var is null: $new_var?
The execution result proves that $ new_var is a null value. I checked on google to find out the problem lies in the pipeline.
Let's take a look at the following content.
The syntax structure of the while loop is as follows:
while test_cmd_list; do cmd_list; done
However, the while loop is more often used to read standard input content to implement loops. There are several ways to write:
Method 1: Use pipelines to transmit content, which is the most widely used but worst-performing Method
echo "abc xyz" | while read line
do
...
done
Statement 2:
while read line
do
...
done <<< "abc xyz"
Statement 3: Read content from a file
while read line
do
...
done </path/filename
Method 4: Process replacement
while read var
do
...
done < <(cmd_list)
Method 5: Change standard input
exec <filename
while read var
do
...
done
Although there are many writing methods, they are not equivalent. The pipeline symbol is used in method 1, which enables the while statement to be executed in the sub-shell. This means that the variables, arrays, and functions set in the while statement do not take effect outside the loop. This is exactly the trap mentioned at the beginning of the article.For the remaining four statements, the while statement is not executed in the sub-shell, so there will be no problems mentioned at the beginning of the article.
For example, use the here string in statement 2 to replace Statement 1:
#!/bin/bashwhile read linedo new_var=$linedone <<< "abc xyz"echo new_var is null: $new_var?
Or use process replacement in Statement 4:
#!/bin/bashwhile read linedo new_var=$linedone < <(echo "abc xyz")echo new_var is null: $new_var?
It can be said that in the above five writing methods, the most widely used method is the simplest and most convenient, but it is actually the worst.
Back to series article outline: http://www.cnblogs.com/f-ck-need-u/p/7048359.html
Reprinted please indicate the source: Success!