通过运行另一个脚本来退出脚本

Ale*_*lls 5 bash shell-script

我在脚本中有这个条件:

if [[ "${SUMAN_ENV}" != "local" ]]; then
 ./suman.sh $@  # run this script instead
 # need to exit here
fi
Run Code Online (Sandbox Code Playgroud)

如果满足条件,我想运行另一个脚本。

这样做的最佳方法是这样做:

if [[ "${SUMAN_ENV}" != "local" ]]; then
 ./suman.sh $@
 exit $?  # exit with the code given by the above command
fi
Run Code Online (Sandbox Code Playgroud)

或者有其他方法吗?

小智 12

文件hello

#!/bin/sh
echo "$0"
exec ./world
echo "$0"
Run Code Online (Sandbox Code Playgroud)

文件world

#!/bin/sh
echo "$0"
exit 33 # to have an exit code example                                                                
Run Code Online (Sandbox Code Playgroud)

运行hello

$ ./hello 
./hello
./world
$ echo $?
33
Run Code Online (Sandbox Code Playgroud)

hello运行world通过execworld完成后,其余部分hello不执行。退出代码是world.

  • @GypsyCosmonaut ... `exit` 就足够了,但在问题的片段中,第一个脚本明确退出,并带有被调用的第二个脚本的退出值。因此,我希望示例中的第二个具有与第一个不同的 `exit` 值,以便具有可区分的值。(那里没有紫色魔法。没有明确的`exit`也可以......) (3认同)
  • `exec` 用指定的进程替换当前运行的进程。PID 不变。原始进程的大部分资源都被释放了。 (2认同)