在 Bash 中,您可以使用以下命令将命令的标准错误输出存储到变量中:`2>&1`
运营商和`$()`
命令替换语法。这里`2>`
将错误消息重定向到&1`
,代表标准输出。在 bash shell 的情况下,它作为标准输出设备。
- For example, to store the standard error output of the
`ls`
command to a variable named errors, you can use the following command:errors=$(ls non-existent-file 2>&1)
或者,您可以使用`$?`
用于将命令的退出状态存储到变量的特殊参数。退出状态是一个数值,指示命令是否成功。值为`0`
表示成功,非零值表示错误。
- 例如,要存储退出状态
`ls`
命令到名为 status 的变量,可以使用以下命令:ls non-existent-file
status=$?
- You can then use the
`$status`
variable to check the exit status of the `ls`
command and take appropriate action based on the result. For example:
|
#!/usr/bin/env bash
# 把你的命令放在这里
if [ $status -ne 0 ]; then
echo “最后一个命令因错误而失败。”
fi
|
请记住,`$()`
命令替换语法允许您执行命令并替换其输出。这`2>`
运算符将命令的标准错误输出重定向到`&1`
Stream,即标准输出流。这允许您在单个变量中捕获命令的标准输出和标准错误输出。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)