【问题标题】:Use bash string to provide multiple arguments to a program, where some argument include whitespace [duplicate]使用 bash 字符串为程序提供多个参数,其中一些参数包括空格 [重复]
【发布时间】:2017-09-15 23:03:02
【问题描述】:

在编写调用wget 的脚本时,我想使用一个包含所有标题的变量,但如果我尝试以下操作,那么标题字符串中的空格会将它们分成多个参数(不是单头):

HEADERS='--header "Accept-Encoding: gzip, deflate"'
wget $HEADERS "$URL"
# ... $HEADERS is interpreted as 4 strings instead of 2 ...
wget --header Accept-Encoding: gzip, deflate http://example.com

我不能将$HEADERS 括在引号中,因为我需要将其解释为 2 个参数而不是 1 个。(如果变量中有许多标题,则需要将其拆分为更多参数。 )

我经常为其他程序编写组装参数的 bash 脚本,我也经常遇到这个问题。 bash 中有解决方案吗?

【问题讨论】:

    标签: bash whitespace


    【解决方案1】:

    不要使用正则变量;使用数组。

    headers=(--header "Accept-Encoding: gzip, deflate")
    wget "${headers[@]}" "$URL"
    

    【讨论】:

      猜你喜欢
      • 2011-05-04
      • 1970-01-01
      • 2014-06-26
      • 1970-01-01
      • 2019-08-14
      • 1970-01-01
      • 2020-04-01
      • 2013-12-11
      • 2013-09-15
      相关资源
      最近更新 更多