How to pass backslashes argument to a script?

跟風遠走 提交于 2021-02-10 23:26:25

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!