问题
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.
回答1:
You have to escape backslashes in the shell: \\
, or put the string in quotes.
For debugging purposes use set -x
.
回答2:
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
来源:https://stackoverflow.com/questions/35722316/how-to-pass-backslashes-argument-to-a-script