makansij
makansij

Reputation: 9865

Do single quotes treat backslashes as special in bash scripting?

From what I've read here it says that "Within single quotes, every special character except ' gets interpreted literally". So, I thought that the backslash ("\") also gets interpreted literally.

But, then when I try to use it in an alias, it somehow still gets interpreted as a special character:

alias somefolder='cd /Some\ path/with\ spaces/'

...still works?

And yet this doesn't:

alias somefolder='cd /Some path/with spaces/'

This surprises me, because I thought the whole point of the single quotes was supposed to be for laziness, i.e. for when you aren't expanding any variables with the $ (because that would require double quotes).

I really doubt that the tldp source is wrong, so is there a better way of explaining this? Thanks.

Upvotes: 1

Views: 79

Answers (2)

Shawn Mehan
Shawn Mehan

Reputation: 4568

Ahh, but the alias you are building is putting out your single quoted var to the cd command, which is choking on your

cd /Some path/with spaces/

because cd doesn't know what to do with the space, not your bash.

When you add the \ to the string as in

'cd /Some\ path/with\ spaces/'

it is cd that is interpreting the \, not the bash which is merely a messenger.

Upvotes: 1

heemayl
heemayl

Reputation: 42017

That's because alias will be expanded by shell, in the process the single quotes will be removed. So after alias expansion you will just have

cd /Some path/with spaces/

remaining which would fail as you have said.

But while you are using \ to escape the spaces, after expanding the alias (and removing single quotes) the shell will have the following to operate on:

cd /Some\ path/with\ spaces/

which would work as expected.

Upvotes: 4

Related Questions