Bash 读取输出?

标签 bash shell

假设我执行了一个 bash 脚本,输出是:

Test1: Some text...
Test2: Some text...
Test3: Some text...

在同一个 bash 脚本中,我如何将上述输出存储为一个或多个变量?

理想的解决方案是让它准备好在这样的条件下使用:(输出的第一行将存储在 $ln1 等中)

if [ $ln1 = "Test1: Some text..." ] ; then

最佳答案

所以你想要

output=$(command)
while IFS= read -r line; do
    process "$line"
done <<< "$output"

参见 Bash manual 中的“这里的字符串” .

process substitution

while IFS= read -r line; do
    process "$line"
done < <(command)

几年后回到这个话题,现在我将命令的输出读入一个数组:

readarray -t lines < <(command)
for line in "${lines[@]}"; do
    do-something-with "$line"
done

关于Bash 读取输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5853400/

相关文章:

Bash 脚本 - 在一个存档中压缩多个目录

作为 jenkins 从机的 Linux/mac 权限

linux - 使用 AWK 组合(合并)多行

macos - 从 OS X 文件引用 URL 别名获取路径(文件 :///. file/id=...)

linux - 使用 shell 脚本搜索和替换文件内容

bash - 连接多个文件

java - Ubuntu 中的 Bash 脚本错误 : awk: line 1: regular expression exceeds implementation size limit

linux - 如何使用 shell 脚本获取进程的所有子进程或孙进程的 pid

python - 以 nohup 启动的进程未与父进程分离

shell - shell脚本中变量的第一个字符为大写?