我有一个 bash 脚本,它使用命令行参数调用/调用子脚本。如何强制子脚本在与调用者相同的 PID 下运行?
答案1
或者,获取子脚本:
一个.sh
#!/bin/sh
echo one.sh: pid is "$$"
. ./two.sh
echo done with "$0"
(命令与中.
完全相同,但更便携)source
bash
.
二.sh
echo two.sh: pid is "$$"
示例运行:
$ ./one.sh
one.sh: pid is 31290
two.sh: pid is 31290
done with ./one.sh
该脚本two.sh
将在与 相同的 shell 环境中运行one.sh
,并且 shell 不会生成新进程来运行它。它的行为非常类似于调用 shell 函数,但方式不止一种(例如,使用return
而不是从早期exit
返回控制权;将完全退出 shell 会话)。two.sh
one.sh
exit
答案2
如果调用子脚本后不需要运行任何其他命令或执行任何其他操作,则可以使用:
exec sub_script
这exec
是一个内置的 shell,它的作用是:
$ help exec
exec: exec [-cl] [-a name] [command [arguments ...]] [redirection ...]
Replace the shell with the given command.
Execute COMMAND, replacing this shell with the specified program.
ARGUMENTS become the arguments to COMMAND. If COMMAND is not specified,
any redirections take effect in the current shell.
Options:
-a name pass NAME as the zeroth argument to COMMAND
-c execute COMMAND with an empty environment
-l place a dash in the zeroth argument to COMMAND
If the command cannot be executed, a non-interactive shell exits, unless
the shell option `execfail' is set.
Exit Status:
Returns success unless COMMAND is not found or a redirection error occurs.
因此,运行后exec sub_script
您就永久离开了父脚本,并且无法再次返回到它。