gpt4 book ai didi

Shell 脚本 : Execute command after running "exit" command in the shell script

转载 作者:行者123 更新时间:2023-12-04 10:54:54 25 4
gpt4 key购买 nike

我有一种情况,我的 shell 脚本中有一个命令必须在 之后执行。退出 命令在同一个脚本中执行(我知道!!听起来很疯狂!!)

我想为类似的事情找到解决方案

#!/bin/sh
ls -l ~/.
exit $?
touch ~/abc.txt

这里我想要命令 touch ~/abc.txtexit $? 之后执行已经运行,命令 touch ~/abc.txt可以是任何命令。

约束: 1) 我无法修改 exit $?上述脚本的一部分。 2) 该命令必须在 exit $? 之后才执行命令。

我不确定是否有解决方案,但任何帮助表示赞赏。

最佳答案

典型的做法是设置陷阱:

trap 'touch ~/abc.txt' 0

这将在 shell 退出时调用 touch 命令。在某些 shell 中(例如 bash ),如果脚本因信号而终止,也会执行陷阱,但在其他 shell 中(例如 dash )则不会。只有当最后一个命令是 exit 时,才没有可移植的方法来调用该命令。 .

关于Shell 脚本 : Execute command after running "exit" command in the shell script,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11687325/

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