linux - 将信息从我的程序传递到调用脚本(退出时)的正确方法是什么

标签 linux shell exit

我想知道,当程序退出时将信息从程序传递到调用脚本的正确方法是什么?假设我有“Program X”和一个应该执行以下操作的 shell 脚本:

1) Call "Program X" that can return with "State A" or "State B"

2) After sucessful execution of "Program X", continue with 3A) or 3B), depending on its return status

3A) Do some things which cannot easily be done in "Program X"

3B) Do some other things which cannot easily be done in "Program X"

当然,我可以简单地使用返回代码来指示 shell 脚本应如何继续。但是,我认为退出代码 0 表示成功,所有其他值表示错误是一个广泛接受的约定。从这个角度来看,使用退出代码来确定后续的控制流(成功执行后)显然是对系统的滥用。

所以我的问题是:实现这一目标的正确方法是什么?

感谢您的任何提示!

最佳答案

这是 shell 中命令替换的一个简单应用。

命令替换

假设 ProgramX3A3B 是您的可执行文件。

无需返回State A/State B,只需根据条件回显3A/3BProgramX 然后只需使用命令替换

$(ProgramX)

上面将相应地运行 3A3B

注意:缺点是您无法将任何其他内容打印到 stdout

<小时/>

编辑:为什么不根据条件将 3A 或 3B 附加到 ProgramX 的末尾

程序X

#at the end
[ 'condition for 3A' ] && 3A 
[ 'condition for 3B' ] && 3B

顺便说一下,你并没有违反任何约定

<小时/>

编辑:退出状态方式

如果您想以退出状态方式执行此操作,则在 ProgramX 中根据条件返回 58 或 59。您实际上可以返回任何内容,但 58 是对应于十六进制 3A 的十进制 #,对应于 3B 的 59。

程序X

#at the end
[ 'condition for 3A' ] && exit 58
[ 'condition for 3B' ] && exit 59

然后做

[ $? -eq 58 ] && 3A
[ $? -eq 59 ] && 3B

关于linux - 将信息从我的程序传递到调用脚本(退出时)的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48259436/

相关文章:

c++ - 在 while 循环中卡住

bash - Unix shell 之间的可移植性——我对这个问题的思考是否正确?

c - quick_exit 和 at_quick_exit 函数有哪些实际应用?

windows - 从函数内部退出批处理脚本

bash - 退出命令在显示服务信息后无法退出 bash shell?

linux - gnuplot - 循环绘图

c - 如何将 C 代码转换为汇编的十六进制表示形式?

linux - 将 stderr 从 cron 重定向到管道

android - 如何使用 adb shell 控制蓝牙操作?

php - 'exec() : Unable to fork' on Ubuntu 14. 04.3 LTS