Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

shell read 逐行读取操作同时修改全局变量的问题 #242

Open
islishude opened this issue Nov 16, 2020 · 0 comments
Open

shell read 逐行读取操作同时修改全局变量的问题 #242

islishude opened this issue Nov 16, 2020 · 0 comments
Labels

Comments

@islishude
Copy link
Owner

islishude commented Nov 16, 2020

当文件没有可读的行时,read 命令将以非零状态退出,所以我们可以使用 while...read 逐行处理数据。

第一种,使用 cat 读取文件然后管道符传给 while...read

cat XXX | while read line;do
    # do anything...
done

第二种,使用输入重定向到 while...read 内

while read line;do
    # do anything...
done<XXX

如果同时操作的全局变量,比如这里有个例子,有一个文件内容需要在每行最后加上逗号 ,,但最后一行不加,最后再就是折叠成一行的内容,如下所示

$ cat text.txt
0
1
2
3
$ ./run.sh
0,1,2,3

那么很简单,如果按照第一种方式,我们可以这样做

#!/bin/sh

result=""

cat text.txt | while read line; do
    if [ -z "$result" ]; then
        result="$line"
    else
        result="$result,$line"
    fi
done

echo $result

但是这种方式永远输出为空,如果换成第二种方式就可以,这是为什么?

当使用pipeline 的时候启动一个子进程,那么这里 result 就相当于一个局部变量,不会修改全局变量。

ref: https://stackoverflow.com/questions/6255303/bash-piping-prevents-global-variable-assignment

@islishude islishude changed the title shell read 逐行读取操作同时全局变量的问题 shell read 逐行读取操作同时修改全局变量的问题 Nov 16, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant