运行直接一个程序和在脚本中调用exec有什么区别?

What is different between running a program directly and calling exec in script?

运行 程序是否有 exec 命令有什么区别?

例如,如果我制作了如下脚本文件。

#script1
python test.py

#script2
exec python test.py

两者似乎 return 相同的结果。

它们等价吗?

exec是一个shell内置的,它将当前进程的图像替换为新进程。它与调用 binary/executable 不同。

要查看差异,请执行以下操作:

#script1
python test.py
echo Hello

#script2
exec python test.py
echo Hello

您不会看到 Hello 在第二个脚本中打印出来。

exec 也是 shell 中的另一个目的。它可以用于重定向。例如,

exec 1>file

将进程的stdout重定向到file

如果你有:

exec 1>file
echo hello 
echo world

然后脚本会将 helloworld 重定向到 file 而不是 stdout.