bash 在 shell 脚本输入中处理特殊字符的简单解决方案
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6243125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple solution for handling special characters in shell script input
提问by Anders
I have a script which can overwrite values in a configuration file using options, for example, option --passwordcan overwrite the setting in the configuration file (please note, this is not a discussion about security). However a password can contain contain characters, that are by bash, recognized as special characters, and those characters needs to be escaped or placed within " ".
我有一个脚本可以使用选项覆盖配置文件中的值,例如,选项--password可以覆盖配置文件中的设置(请注意,这不是关于安全性的讨论)。但是,密码可以包含被bash识别为特殊字符的字符,这些字符需要转义或放置在“”中。
Now I understand this. Although I can't say whom will be using this script in the future, so I would like to save he or she the trouble of having an incorrect password simply because, he or she forgot to place the password within " " or escape the special character.
现在我明白了。虽然我不能说将来谁会使用这个脚本,所以我想省去他或她因为忘记将密码放在“特点。
What is the best way of dealing with such an input?
处理此类输入的最佳方法是什么?
Thanks in advance.
提前致谢。
回答by jm666
Hm.. Double quotes are not enough. Must use single quotes, because the rare situation, for example
嗯.. 双引号是不够的。必须使用单引号,因为很少见的情况,例如
mycommand --password "AAA$PWD" #is worng for any exported environment varname
mycommand --password 'AAA$PWD' #ok
Here is no wayavoid this, because your users using a sort of shell, what have variable expansions and metachar-globbing. Your command getting already expanded args, so here is no way catch this in your script.
这是无法避免的,因为您的用户使用一种外壳,具有变量扩展和元字符通配符。您的命令已经扩展了 args,因此无法在您的脚本中捕获它。
The only way - as @Bohemian told above - reading the password from a tty. You can write a simple wrapper around your current script, what will read the password from a tty and after will execute your script with properly escaped --pasword argument.
唯一的方法 - 正如@Bohemian 上面所说的 - 从 tty 读取密码。您可以围绕当前脚本编写一个简单的包装器,它将从 tty 读取密码,然后使用正确转义的 --pasword 参数执行您的脚本。
回答by Derzu
There is a simple, but not very intuitive solution.
有一个简单但不是很直观的解决方案。
Encapsulate the character that is causing problem with '"CARACTER"'. And put all the password string between single quotes.
封装导致“CARACTER”问题的字符。并将所有密码字符串放在单引号之间。
In my case the character that was causing the problem was the ' (single quote).
在我的情况下,导致问题的字符是 '(单引号)。
So if I have a command like that:
所以如果我有这样的命令:
mycommand --password 'AAA'PWD'
Replace by that:
替换为:
mycommand --password 'AAA'"'"'PWD'
Now my password is a concatenation of three strings. Explanation:
现在我的密码是三个字符串的串联。解释:
'AAA' + "'" + 'PWD' # plus sign is just to make clear the contatenation.
That's works.
那是有效的。

