我有很多bash脚本,每个脚本都快乐地做着自己的事情。请注意,当我用其他语言编程时,我只使用Bash来自动化事物,并且不是很擅长。
我现在正试图将其中的一些组合起来创建" meta"脚本,如果你愿意,它使用其他脚本作为步骤。问题是我需要解析每个步骤的输出,以便能够将其中的一部分作为参数传递给下一步。
一个例子:
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
的脚本,并使用每个脚本的输出执行自己的操作。我目前正在做的事情(以上脚本都符号链接到/ 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
s?
提前致谢!
答案 0 :(得分:4)
由于您明确使用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'*}"