Bash:在带空格的字符串中添加额外的单引号 [英] Bash : Adding extra single quotes to strings with spaces
问题描述
当我尝试将参数作为变量传递给bash中的任何命令时,如果变量值有空格,我会看到bash添加了额外的引号.
When I try to passing arguments as variables to any commands in bash I can see extra quotes added by bash if the variable value has spaces.
我正在创建文件"some file.txt",并将其添加到变量$ file中. 我正在使用$ file并将其存储在另一个变量$ arg中,并在$ file上加上引号. 我希望通过bash进行变量扩展后的命令是
I am creating a file "some file.txt" and adding it to a variable $file. I am using $file and storing it in another variable $arg with quotes on $file. The the command I am hoping for after variable expansion by bash was
find . -name "some text.txt"
但是我遇到错误,实际执行的文件是
but I got error and actual file that got executed is,
find . -name '"some' 'file.txt"
为什么会这样.在这种情况下,bash变量展开是如何工作的?
Why is this happening. How bash variable expanson works in this case?
$ 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]
为什么会这样?
推荐答案
扩展参数后,将参数值中的引号视为文字字符.您的尝试与
Quotes in the value of a parameter are treated as literal characters after the parameter is expanded. Your attempt is the same as
find . -name \"some file.txt\"
不是
find . -name "some file.txt"
要处理包含空格的参数,您需要使用一个数组.
To handle arguments containing whitespace, you need to use an array.
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[@]}"
这篇关于Bash:在带空格的字符串中添加额外的单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!