将特殊字符从输入传递到 bash 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23779744/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:30:04  来源:igfitidea点击:

pass special characters from input to bash script

bashshellspecial-characters

提问by gaspar

I've a bash script that simple has to add new user and sign a password that is passed when script is called:

我有一个简单的 bash 脚本,必须添加新用户并签署调用脚本时传递的密码:

./adduser_script username password

and the password is then used as a parameter in the script like this:

然后将密码用作脚本中的参数,如下所示:

/usr/sbin/useradd ... -p `openssl passwd -1 ""` ...

the problem occurs of course when password contains special characters like $@, $* itd. So when i call the script:

当密码包含特殊字符(如 $@、$* itd)时,当然会出现问题。所以当我调用脚本时:

/adduser_script username aa$@bbb

and after script ends password looks like: aabbb (so the special charakters are removed from original password). The question is how can I correctly pass the original password with special charakters to the script?

脚本结束后密码看起来像:aabbb(因此特殊字符从原始密码中删除)。问题是如何将带有特殊字符的原始密码正确传递给脚本?

Thanks in advance, Regards

提前致谢, 问候

采纳答案by Jacobo de Vera

The problem is probably not in your script at all, but rather on how you call it. At least from the snippets you provide, it doesn't seem like the password field is being evaluated.

问题可能根本不在您的脚本中,而在于您如何调用它。至少从您提供的片段来看,似乎没有对密码字段进行评估。

So, when you call the script, if an argument contains something like $a, bash will replace it with the value of the variable a, or an empty string if it is unset.

因此,当您调用脚本时,如果参数包含诸如 $a 之类的内容,bash 会将其替换为变量的值,a如果未设置,则替换为空字符串。

If $needs to be in the password, then it needs to be in single quotes.

如果$需要在密码中,则需要在单引号中。

./adduser_script username 'password$@aaa'

回答by Amit Kumar

have you tried strong qoutes ??

你有没有试过强大的 qoutes ?

use 'aa$@bb' instead of weak qoutes i.e. "aa$@bb"

使用 'aa$@bb' 而不是弱 qoutes,即“aa$@bb”

for example: check with echo command

例如:使用 echo 命令检查

echo "aa$@bb" will print aabb

while

尽管

echo 'aa$@bb' will print aa$@bb

In your script use

在你的脚本中使用

/usr/sbin/useradd ... -p `openssl passwd -1 ''` ...

now you need not to worry about qoutes while passing password as argument.

现在您在将密码作为参数传递时无需担心 qoutes。

回答by Jain Rach

You can also use double quotes with escape . For example: set password "MyComplexP\@\$\$word"

您还可以将双引号与 escape 一起使用。例如:设置密码“MyComplexP\@\$\$word”

回答by Chris Franklin

/usr/sbin/useradd ... -p "$(openssl passwd -1 '')"