【问题标题】:Bash execute string as command without expanding escaped spaces [duplicate]Bash将字符串作为命令执行而不扩展转义空格[重复]
【发布时间】:2020-09-01 19:55:45
【问题描述】:

我有一个需要向其传递参数的外部可执行文件。使用 bash 脚本,我有确定这些参数的代码。一些参数可能已经转义了空格。 然后我需要执行该字符串,而不扩展每个参数。

# ... some code that determines argument string
# the following is an example of the string

ARGSTR='./executable test\ file.txt arg2=true'
exec ${ARGSTR}

我必须扩展$ARGSTR,以便我可以将参数传递给./executable,但每个参数都不应扩展。我试过引用"test file.txt",但这仍然没有将它作为一个参数传递给./executable

有没有办法做这样的事情?

【问题讨论】:

  • 使用函数而不是变量?
  • thisthisthisthis 和许多其他的可能重复。 (警告:其中一些答案涉及eval - 不要被诱惑,eval 通常会导致奇怪的错误)。

标签: string bash command-line-arguments


【解决方案1】:

我们使用数组而不是字符串:

#!/usr/bin/env bash

ARGSTR=('./executable' 'test file.txt' 'arg2=true')
exec "${ARGSTR[@]}"

见:

BashFAQ-50 - 我正在尝试将命令放入变量中,但复杂的情况总是失败。

https://stackoverflow.com/a/44055875/7939871

【讨论】:

    【解决方案2】:

    这可能会达到你想要的:

    ARGSTR='./executable test\ file.txt arg2=true'
    exec bash -c "exec ${ARGSTR}"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-19
      • 1970-01-01
      • 1970-01-01
      • 2011-02-20
      • 1970-01-01
      • 2010-10-05
      • 1970-01-01
      相关资源
      最近更新 更多