bash - 将 bash 中的命令输出解析为变量

标签 bash

我有许多 bash 脚本,每个脚本都在愉快地做自己的事情。请注意,虽然我用其他语言编程,但我只使用 Bash 来自动化操作,而且不太擅长。

我现在正在尝试将其中的一些脚本组合起来创建“元”脚本(如果您愿意的话),该脚本使用其他脚本作为步骤。问题是我需要解析每个步骤的输出,以便能够将其中的一部分作为参数传递到下一步。

一个例子:

stepA.sh

[...does stuff here...]
echo "Task complete successfuly"
echo "Files available at: $d1/$1"
echo "Logs available at: $d2/$1"

以上都是路径,例如/var/www/thisisatest 和/var/log/thisisatest (请注意,文件始终以/var/www 开头,日志始终以/var/log 开头)。我只对文件路径感兴趣。

steB.sh

[...does stuff here...]
echo "Creation of $d1 complete."
echo "Access with username $usr and password $pass"

这里的所有变量都是简单的字符串,可能包含特殊字符(没有空格)

我正在尝试构建一个脚本,该脚本运行 stepA.sh,然后运行 ​​stepB.sh 并使用每个脚本的输出来执行自己的操作。我目前正在做的事情(上面的两个脚本都符号链接(symbolic link)到/usr/local/bin ,没有 .sh 部分并可执行):

 #!/bin/bash

 stepA $1 | while read -r line; do
 # Create the container, and grab the file location
 # then pass it to then next pipe
   if [[ "$line" == *:* ]]
   then
     POS=`expr index "$line" "/"`
     PTH="/${line:$POS}"
     if [[ "$PTH" == *www* ]]
     then
       #OK, have what I need here, now what?
       echo $PTH;
     fi
   fi
done 

# Somehow get $PTH here

stepB $1 | while read -r line; do
 ...
done

#somehow have the required strings here

我陷入了将 PTH 传递到下一步的困境。我明白这是因为管道在子 shell 中运行它,但是我看到的所有示例都引用文件而不是命令,并且我无法使其工作。我尝试将 echo 通过管道传输到“下一步”,例如

stepA | while ...
    echo $PTH
done | while ...
 #Got my var here, but cannot run stuff
done

如何运行 stepA 并让 PTH 变量可供稍后使用? 有没有比嵌套 if 更好的方法来从输出中提取我需要的路径?

提前致谢!

最佳答案

由于您显式使用 bash(在 shebang 行中),因此您可以使用其进程替换功能而不是管道:

while read -r line; do
    if [[ "$line" == *:* ]]
        .....
    fi
done < <(stepA $1)

或者,您可以将命令的输出捕获到字符串变量,然后解析它:

output="$(stepA $1)"
tmp="${output#*$'\nFiles available at: '}" # output with everything before the filepath trimmed
filepath="${tmp%%$'\n'*}" # trim the first newline and everything after it from $tmp
tmp="${output#*$'\nLogs available at: '}"
logpath="${tmp%%$'\n'*}"

关于bash - 将 bash 中的命令输出解析为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15309818/

相关文章:

linux - 移动时附加而不是覆盖文件

linux - 如何将 file1 的每一列附加到 file2 的特定字段并制作新的输出文件?

bash - 非交互式 bash 中的别名

bash - 如何将语法突出显示添加到 make 错误消息中?

bash - 使用 Mac 从命令行配置网络首选项

regex - 如何删除与模式匹配的特定数量的随机行

bash - Unix中过滤/etc/passwd

linux - 使用 cronjob 只运行一次 shell 脚本

bash - 删除空格分隔的文本文件中某些索引处的条目

linux - 将 PATH 环境变量导入到使用 cron 启动的 Bash 脚本中