Bash:为带空格的字符串添加额外的单引号

ano*_*abu 3 bash variable-expansion

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

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

find . -name "some text.txt"
Run Code Online (Sandbox Code Playgroud)

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

find . -name '"some' 'file.txt"
Run Code Online (Sandbox Code Playgroud)

为什么会这样呢?在这种情况下,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]
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

che*_*ner 5

扩展参数后,参数值中的引号将被视为文字字符.你的尝试与之相同

find . -name \"some file.txt\"
Run Code Online (Sandbox Code Playgroud)

find . -name "some file.txt"
Run Code Online (Sandbox Code Playgroud)

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

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[@]}"
Run Code Online (Sandbox Code Playgroud)