linux - 如何将退出代码传递给 bash 中的函数?

标签 linux bash

假设我在 bash 中有这个日志记录功能。

function report {
    echo "Log message: [$@]  time:  " `date` >> reports.txt
}

每次我需要的时候我都会这样调用它。

report running python 
python3 script.py 
report python script ended

现在,我还想记录来自 script.py 的现有代码的日志消息

我显然可以使用 report python 脚本以 $ 结尾来做到这一点?退出代码 但是有没有办法不显式传递这样的参数,而是从函数报告中获取它?

我试过了

...
echo "Log message: [$@]  time:  " `date`  with exit code $? >> reports.txt
... 

但即使脚本失败,我总是得到0

最佳答案

$? 在您运行另一个命令之前不会重置,因此您应该能够将其捕获为 report 的第一个操作:

report () {
    status=$?
    ...
    printf 'Log message: [%s] time: %s with exit code %d\n' "$1" "$(date)" "$status"
}

请注意,您应该将日志消息作为单个参数传递,而不是作为任意单词序列传递。

report "running python"
python3 script.py
report "python script ended"

不过,将退出状态直接作为参数传递可能会更清晰,例如,python3 script.py;状态=$?; ...;报告“python 脚本结束”“$status”。这使您不必确保在要记录其状态的命令之后立即调用report。 (这还允许您忽略不适用的状态,就像 script.py 之前的调用一样。)

关于linux - 如何将退出代码传递给 bash 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36433643/

相关文章:

具有较小学习曲线的 C++ 图形 API - linux

php - Linux 上的 Swift Mailer 错误

linux - Linux 变量/数组分配中的 Bash 脚本

bash - 使用 docker 运行容器时出错

bash - 如何在 Bash 中打印函数定义?

php - 500 内部服务器 - Apache

linux - bash进程中文件描述符255有什么用

linux - ASP.NET Core 1.0.1 不适用于 Ubuntu/Linux?

linux - 对包含域名的输入文件执行质量扫描

python - 如何将错误消息从 shell 脚本传递到 Python 脚本?