Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass backslashes argument to a script?

Tags:

bash

shell

sh

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.

like image 373
DontVoteMeDown Avatar asked Oct 28 '25 15:10

DontVoteMeDown


2 Answers

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

For debugging purposes use set -x.

like image 157
Karoly Horvath Avatar answered Oct 31 '25 04:10

Karoly Horvath


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

like image 24
edi9999 Avatar answered Oct 31 '25 04:10

edi9999