将"No such file or directory"消息存储在变量中



我有一个脚本,它在内部调用另一个shell脚本。第二个脚本可能不存在。之后我想写有条件执行。我如何存储消息";没有这样的文件或目录";变量内部?

OUTPUT=$(sh ../../bin/tools/myscript.sh)
sh: ../../bin/tools/myscript.sh: No such file or directory
[root@xxxx home]# echo $OUTPUT

$OUTPUT还应该打印";没有这样的文件或目录";消息

消息已打印到stderr,因此您必须以某种方式捕获stderr:

OUTPUT=$(sh ../../bin/tools/myscript.sh 2>&1)

或者类似的东西

error_file=/tmp/stderr.$$
sh ../../bin/tools/myscript.sh 2>$error_file
OUTPUT=$(cat $error_file)
rm $error_file

取决于您的具体需求。当然,在您的情况下,在运行myscript.sh之前测试它的存在可能更有意义

以下代码对我有效:

OUTPUT=$((sh ../../bin/tools/myscript.sh) 2>&1)

最新更新