【问题标题】:Shell logout after exec redirection for stdin执行 stdin 重定向后的 Shell 注销
【发布时间】:2013-05-19 03:16:36
【问题描述】:

如高级 bash 脚本指南中所述,exec 可用于重定向 I/O。 所以我只是在我的shell中写了一些案例。重定向 stdout 或 stderr 效果很好,但重定向 stdin 会使 shell 注销。有什么解释吗?

命令:

exec < file

【问题讨论】:

  • 就像运行命令'exit'

标签: bash shell exec


【解决方案1】:

shell 在其标准输入到达 EOF 时退出(这就是您键入 Control-D 注销的原因)。当它从file读完后,它将退出,因为没有更多的输入。

【讨论】:

  • e...我只是重定向标准输入并没有从输入中读取任何内容,它如何完成从文件中读取?
  • 重定向后,shell 不再从终端读取;它正在从文件中读取。完成读取文件后,它不会再次开始从终端读取:它退出了。
  • @chepner 说得通。
  • 作为@chepner sadi,重定向后脚本继续执行;来自标准输入的任何进一步输入都来自文件而不是终端。当文件不再有输入时,它将终止。确切的方式和时间取决于执行的命令和它们读取的内容,但是当没有更多可用输入时,shell 将最终退出。
【解决方案2】:

来自 bash 的 BASH_BUILTINS 手册页 (man exec)

   exec [-cl] [-a name] [command [arguments]]
          If command is specified, it replaces the shell.  No new  process
          is  created.  The arguments become the arguments to command.  If
          the -l option is supplied, the shell places a dash at the begin-
          ning  of  the  zeroth  argument passed to command.  This is what
          login(1) 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 the executed command.  If command can-
          not  be executed for some reason, a non-interactive shell exits,
          unless the shell option execfail is enabled, in  which  case  it
          returns  failure.   An  interactive shell returns failure if the
          file cannot be executed.  If command is not specified, any redi-
          rections take effect in the current shell, and the return status
          is 0.  If there is a redirection error, the return status is  1.

所以,如您所见,如果命令完成 -> 退出,如果命令失败 -> 退出...
将文件重定向到 exec 将失败...
除非它包含的有效代码行也在您退出之前不会退出。
(否则它将运行并退出...)

【讨论】:

    猜你喜欢
    • 2012-11-05
    • 2021-12-09
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 2011-06-15
    • 2015-10-05
    • 2018-12-10
    • 2018-07-21
    相关资源
    最近更新 更多