【问题标题】:How to call a bash script that has getopts with curl command?如何使用 curl 命令调用具有 getopts 的 bash 脚本?
【发布时间】:2014-08-04 13:30:05
【问题描述】:

我有一个包含简单“getopts”的脚本。

我发现只有这样称呼它才有效:

bash <(http://domain.com/myscript.sh) -a

为什么这样称呼它不起作用?

curl –L http://domain.com/myscript.sh | bash -s -a

curl 有什么不同的调用方式吗? (除了我提供的)

我不想下载它,只想使用 curl 来执行它。

#!/bin/bash
while getopts ":a" opt; do
  case $opt in
    a)
      echo "-a was triggered!" >&2
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      ;;
  esac
done

【问题讨论】:

    标签: linux bash shell curl getopts


    【解决方案1】:

    看来-s 之后以- 开头的参数仍会被解析为 bash 的选项(请参阅help set):

    printf "arguments: %s\n" "$*"
    shopt -o | grep noglob
    

    测试:

    $ bash -s -f < script.sh
    arguments: 
    noglob          on
    $ bash -s -a < script.sh
    arguments: 
    noglob          off
    $ bash -s -z < script.sh
    bash: -z: invalid option
    $ bash -s x < script.sh
    arguments: x
    noglob          off
    

    为了防止它,只需使用--

    curl –L http://domain.com/myscript.sh | bash -s -- -a
    

    来自 bash 的手册:

    A -- 表示选项结束并禁用更多选项 加工。 -- 之后的任何参数都被视为文件名和 论据。 - 的参数等价于 --。

    #!/bin/bash
    while getopts ":a" opt; do
      case $opt in
        a)
          echo "-a was triggered!" >&2
          ;;
        \?)
          echo "Invalid option: -$OPTARG" >&2
          ;;
      esac
    done
    

    测试:

    $ bash script.sh -s -- -a < script.sh
    -a was triggered!
    

    【讨论】:

    • @AsafMagen 我希望你能接受答案,如果它足够了:)
    • 我愿意。我需要做点什么吗?
    【解决方案2】:

    简单:

    curl -L http://domain.com/myscript.sh | bash /dev/stdin -a
    

    【讨论】: