epon
epon

Reputation: 21

Bash nested double-quoting word split inconsistency

I've been messing around with bash quoting and have noticed the following oddity which seems to show inconsistent behaviour and was wondering if anyone can explain what is going on?:

If I do a test with cp using nested double quotes:

$ filename="file name"
$ cp "/a/path/to/"${filename}"" /tmp
+ cp /a/path/to/file name /tmp
cp: cannot stat '/a/path/to/file': No such file or directory
cp: cannot stat 'name': No such file or directory

Ok so it's splitting the words - seems reasonable if you consider the " character as a toggle on/off for quoting and read left-to-right.

Interestingly the word-splitting here works as expected:

$ cp "/a/path/to/${filename}" /tmp
+ cp '/a/path/to/file name /tmp'
cp: cannot stat '/a/path/to/file name': No such file or directory

OK, so why doesn't a variable assignment behave the same way? e.g.

pathname="/a/path/to/"${filename}"" 

surely should be the same as typing:

$ pathname=/a/path/to/file name
+ pathname=/a/path/to/file
+ name
-bash: name: command not found

but what actually happens is:

$ pathname="/a/path/to/"${filename}""
+ pathname='/a/path/to/file name'

It works fine?!

Quoting behaviour seems inconsistent between variables and commmands.

Upvotes: 1

Views: 114

Answers (1)

Peter Bowers
Peter Bowers

Reputation: 3093

It has to do with the way BASH does the expansion across the line.

If you read here you will see that the first step is setting aside anything that looks like word=word and then the rest of the line is parsed.

Apparently your

$ pathname="/a/path/to/"${filename}""

is interpreted simply as word=word and saved for processing later on in the expansion process. When it gets to that later step it expands the contained variable and does the assignment and you end up with voila a perceived inconsistency.

Upvotes: 1

Related Questions