首页 > 解决方案 > #!/bin/sh 之后的破折号'-' -

问题描述

我一直在 CentOS 7 上编写一些脚本,有时我会看到:

#!/bin/sh -

在第一行。查看手册页,sh我在Special Parameters

   -      Expands to the current option flags as  specified  upon  invocation,
          by  the  set  builtin  command, or those set by the shell
          itself (such as the -i option).

这到底是什么意思?我什么时候需要使用这个特殊的参数选项??

标签: shellcentossh

解决方案


您正在阅读的文档与您正在查看的命令行无关:它指的是特殊变量。在这种情况下,如果您运行,echo $-您将看到“调用时指定的当前选项标志...”。

如果您查看手册页的OPTIONS部分bash,您会发现:

--       A -- signals the end of options and disables  further  option  processing.
         Any  arguments  after  the  -- are treated as filenames and arguments.  An
         argument of - is equivalent to --.

换句话说,一个参数的-简单意思是“在这个参数之后没有其他选项”。

您经常会看到这用于您希望避免以-意外将文件名开头的文件名视为命令选项的情况:例如,如果-R在当前目录中命名了一个文件,则运行ls *实际上将表现为ls -R并产生递归列表,而ls -- *不会-R特别对待文件。

在该#!行中使用单破折号是为了安全防范。您可以在此处阅读更多相关信息。


推荐阅读