Recently, a shell script has been implemented. Simply speaking, it reads all the lines from the file and writes them into a file. The key code is as follows.
path_all="" cat $1 | while read line do if [ "$path_all" == "" ];then path_all=$line else path_all=$path_all,$line fi done echo $path_all > $one_file
The result of execution is empty! According to common sense, the variables in shell are global variables by default, and there is no problem of variable scope. So, after checking on the internet, we find that the problem lies on while.
There are two ways to read the contents of a file in a while loop, one is the pipe character, the other is the redirection, which is written as follows
cat $file_name | while read line do #deal with line done
while read line do #deal with line done < $file_name
The difference between the two approaches is that redirection is a built-in command, and the pipe symbol is a non-built command.
That’s why the output of my script is empty
When Linux executes a shell, it creates a “child shell” to run the commands in the shell, and when it runs to non-built instructions, it creates a “grand shell” to run non-built instructions.
The function of variables is valid in each shell, so those variables defined in non-built instructions can only run in the grand shell, but not in the sub-shell, so even if I assign path_all in while, this value will not be obtained in the sub-shell.
There are two ways to solve this problem, as follows
If you don’t have to write a while loop in a pipe character way, you can write it in a redirected way. The variables in the loop are valid in the sub-shell and are relatively simple.
If you have to use pipe characters, you can create temporary files to store output in your Sun shell
cat $file_name | while read line do echo $line >> $tmp_file done cat $tmp_file >$one_file
Although both approaches can solve this problem, the first solution is recommended.
In this article, the scope of variables in shell loop is discussed, which is the whole content shared by the editor. I hope to give you a reference, and I hope you can support developpaer more.