“ bash-”中的“-”是什么意思?


33

bash -以下bash shell代码是什么意思?它似乎用于将输出的最后一个代码作为输入。如果是这样,我可以只写为bash还是xargs bash

curl --silent --location https://rpm.nodesource.com/setup | bash -

Answers:


36

如有疑问,请阅读源代码。=)

Bash 4.3中的shell.c第830行parse_shell_options()

  /* A single `-' signals the end of options.  From the 4.3 BSD sh.
     An option `--' means the same thing; this is the standard
     getopt(3) meaning. */
  if (arg_string[0] == '-' &&
       (arg_string[1] == '\0' ||
         (arg_string[1] == '-' && arg_string[2] == '\0')))
    return (next_arg);

换句话说,这-就是说没有更多选择。如果命令行上还有其他单词,即使这些单词以a开头,它们也将被视为文件名-

当然,在您的示例中,这-完全是多余的,因为无论如何都没有遵循它。换句话说,bash -与完全等效bash


Bash接受命令

  1. 从脚本文件(如果在命令行中提供),或者
  2. 如果它的stdin不是TTY(例如在您的示例中:stdin是一个管道,则Bash将以脚本的形式执行该URL的内容),从其stdin非交互地进行操作,或者
  3. 如果其stdin是TTY,则进行交互。

bash -告诉Bash从其标准输入中读取其命令是一种误解。虽然这事实,在你的榜样,bash将标准输入读取它的命令,就已经这样做了,无论是否有一个-命令行上,因为,如上所述,bash -是相同的bash

为了进一步说明这-并不意味着stdin,请考虑:

  • cat命令旨在将a解释-为stdin。例如:

    $ echo xxx | cat /etc/hosts - /etc/shells
    127.0.0.1 localhost
    xxx
    # /etc/shells: valid login shells
    /bin/sh
    /bin/dash
    /bin/bash
    /bin/rbash
    /bin/zsh
    /usr/bin/zsh
    /usr/bin/screen
    /bin/tcsh
    /usr/bin/tcsh
    /usr/bin/tmux
    /bin/ksh93
  • 相反,你不能击来执行/bin/date,然后/bin/hostname通过尝试这样的:

    $ echo date | bash - hostname
    /bin/hostname: /bin/hostname: cannot execute binary file

    而是尝试将其解释/bin/hostname为Shell脚本文件,该文件失败,因为它是一堆二进制gobbledygook。

  • 您不能date +%s使用bash -两者执行。

    $ date +%s
    1448696965
    $ echo date | bash -
    Sat Nov 28 07:49:31 UTC 2015
    $ echo date | bash - +%s
    bash: +%s: No such file or directory

你能写xargs bash吗?否。 curl | xargs bash将使用脚本内容作为命令行参数调用bash。内容的第一个单词将是第一个参数,并且可能会被误解为脚本文件名。


6
支持唯一正确的答案。
盖尔哈2015年

确实:用联机帮助的话说An argument of - is equivalent to --.
steeldriver

如果您确实想使用xargs它,则可以使用(在输入脚本足够小的情况下)使用| xargs bash -c; 但这确实不是的有用或惯用用法xargs
2015年

@tripleee如果URL的内容不仅仅是单行,那么换行符和其他定界符可能都是错误的。
200_success 2015年

h,您当然是对的。
2015年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.