8

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?

2

1 Answer 1

9

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[@]}"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.