Bash : Adding extra single quotes to strings with spaces
Asked Answered
E

1

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?

Enphytotic answered 23/11, 2015 at 12:49 Comment(2)
I'm trying to put a command in a variable, but the complex cases always fail!Enchantress
This kind of annoying stuff is why, after about 1 hour of shell scripting, I always slam my head into a wallEpinephrine
N
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[@]}"
Nunhood answered 23/11, 2015 at 12:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.