DontVoteMeDown
DontVoteMeDown

Reputation: 21465

How to pass backslashes argument to a script?

I just want to append an user input argument in a text file. I'm using the following command:

echo "$2" >> "./db.txt"

$2 is expected to user to set a path like: D:\Projects\MyProject. It writes to the file, but with no backslashes. The result is:

D:ProjectsMyProject

I can't find anywhere how to fix that. I've tried using -e or -E params(taken from here) but it doesn't seems to make difference in this case.

Upvotes: 4

Views: 8043

Answers (2)

edi9999
edi9999

Reputation: 20554

echo 'foo\bar\baz' will show foo\bar\baz

When using no quotes at all for your arguments, some characters have special meaning , for example $ means variable as in $HOME. Space is the argument separator, so if you want to pass it as one argument, you have to escape that too.

You can use strong quoting to not have to quote the backslaches (for example'foo\bar') . Inside strong-quoted strings, the only character which has special meaning is ', which means that it is the only character that has to be escaped if you want to put it into a screen.

So echo 'foo\bar\baz' will show foo\bar\baz

Upvotes: 1

Karoly Horvath
Karoly Horvath

Reputation: 96266

You have to escape backslashes in the shell: \\, or put the string in quotes.

For debugging purposes use set -x.

Upvotes: 6

Related Questions