gaspar
gaspar

Reputation: 734

pass special characters from input to bash script

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

./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 "$2"` ...

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

/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?

Thanks in advance, Regards

Upvotes: 7

Views: 19015

Answers (5)

Natnael Sisay Kagnaw
Natnael Sisay Kagnaw

Reputation: 31

I have been facing similar issue and here is my in take on it. One thing we need to consider is the user of single and double quotes in our script file.

if we put a value, variable in single quote the value will be as it is and it will not be replaced with actual value we reference.

example,

name='java'

echo '$name' ---> prints $name to console , but

echo "$name" ---> prints java to console.

So, play around on which quote is best to used based on your circumstance.

Upvotes: 0

Jain Rachit Kumar
Jain Rachit Kumar

Reputation: 4277

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

Upvotes: 1

Chris Franklin
Chris Franklin

Reputation: 1

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

Upvotes: -1

Amit Kumar
Amit Kumar

Reputation: 313

have you tried strong qoutes ??

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

for example: check with echo command

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 '$2'` ...

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

Upvotes: 5

Jacobo de Vera
Jacobo de Vera

Reputation: 1933

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.

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

./adduser_script username 'password$@aaa'

Upvotes: 3

Related Questions