gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:55:17 25 4
gpt4 key购买 nike

我想知道,当程序退出时将信息从程序传递到调用脚本的正确方法是什么?假设我有“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com