了解执行命令

Understanding exec command

在shell编程方面寻求一些基本帮助。

假设我们有一个名为foobar的命令,那么shell调用

的效果是什么
  1. exec foobar
  2. exec 2> /var/log/foobar.log
exec foobar

将用 foobar 替换您的 shell 进程。我不认为你的意思是 exec 2>/var/log/foobar.log,而是 exec foobar 2>/var/log/foobar.log。这将与发送 2 相同,即标准错误消息到指定的日志文件。您可以阅读手册页 here

exec(1)命令类似于exec(3)调用。它从被调用程序的代码段中替换调用进程的代码段。 1 和 3 表示手册页部分。

第一个 exec 命令只能在脚本中使用——不能在命令行终端中使用。它将 shell 替换为程序 foobar,而不是 运行,它作为一个单独的子进程。 exec foobar之后脚本中的任何命令都不会执行(即使shell找不到foobar执行);如果是交互式终端会话,会报错并继续。

exec [-cl] [-a name] [command [arguments]]

If command is supplied, it replaces the shell without creating a new process. If the -l option is supplied, the shell places a dash at the beginning of the zeroth argument passed to command. This is what the login program does. The -c option causes command to be executed with an empty environment. If -a is supplied, the shell passes name as the zeroth argument to command. If command cannot be executed for some reason, a non-interactive shell exits, unless the execfail shell option is enabled. In that case, it returns failure. An interactive shell returns failure if the file cannot be executed.

第二个 exec(使用 I/O 重定向但没有命令)改变了一些东西,以便标准错误流转到文件 /var/log/foobar.log。来自 shell 或由 shell 执行的命令的任何进一步错误消息都将转到日志文件(除非还有很多 I/O 重定向)。

If no command is specified, redirections may be used to affect the current shell environment. If there are no redirection errors, the return status is zero; otherwise the return status is non-zero.