问题
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.
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"
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]
Why this is happening?
回答1:
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\"
not
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[@]}"
来源:https://stackoverflow.com/questions/33871500/bash-adding-extra-single-quotes-to-strings-with-spaces