【问题标题】:Bash : Adding extra single quotes to strings with spacesBash:向带有空格的字符串添加额外的单引号
【发布时间】:2016-02-25 14:04:18
【问题描述】:

当我尝试将参数作为变量传递给 bash 中的任何命令时,如果变量值有空格,我可以看到 bash 添加的额外引号。

我正在创建一个文件“some file.txt”并将其添加到变量 $file。 我正在使用 $file 并将其存储在另一个变量 $arg 中,并在 $file 上加上引号。 我希望通过 bash 进行变量扩展后的命令是

find . -name "some text.txt"

但我得到了错误,实际执行的文件是,

find . -name '"some' 'file.txt"

为什么会这样。在这种情况下 bash 变量 expanson 是如何工作的?

$ touch "some file.txt"
$ file="some file.txt"
$ arg=" -name \"$file\""

$ find . $arg
find: paths must precede expression: file.txt"
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

$ set -x
$ find . $arg
+ find . -name '"some' 'file.txt"'
find: paths must precede expression: file.txt"
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

为什么会这样?

【问题讨论】:

标签: bash variable-expansion


【解决方案1】:

参数值中的引号在参数展开后被视为文字字符。你的尝试是一样的

find . -name \"some file.txt\"

不是

find . -name "some file.txt"

要处理包含空格的参数,您需要使用数组。

file="some file.txt"
# Create an array with two elements; the second element contains whitespace
args=( -name "$file" )
# Expand the array to two separate words; the second word contains whitespace.
find . "${args[@]}"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2019-12-11
    相关资源
    最近更新 更多