Reputation: 1
I am currently learning how to use perl and how to begin to shellscript. I am trying to send via echo a code snip to another shell script that crypts a password to then be used to add a new user in linux. The snippit:
echo "pass=\$(perl -e 'print crypt(\"password\", \"password\")' $password)" >> /home/testscript.sh
which will use the following command to add a new user:
/usr/sbin/useradd -m -p \$pass testuser
My question is: why all the backslashes? Like \&(perl
, \"password\"
, and \$pass
in the add user code? Are they needed? Or could I just have:
echo "pass=$(perl -e 'print crypt("password", "password")' $password)"
/usr/sbin/useradd -m -p &pass testuser
Upvotes: 0
Views: 606
Reputation: 1100
The one liner you posted is fairly complex, it nests a bunch of commands, this nesting leads to all the backslashes.
Breaking it down will probably make it clear for you.
From bash (or similar) you have
$password = 'ABC123'; # set somewhere, using a constant for clarity
echo "pass=\$(perl -e 'print crypt(\"password\", \"password\")' $password)" >> /home/testscript.sh
This adds the following line to testscript.sh, probably a bash shell script
pass=$(perl -e 'print crypt("password", "password")' ABC123)
Note that we have stripped all the slashes away and the password has been supplied.
The first half of this can then be executed as a one line perl script.
print crypt("password", "password")
This uses the C library crypt function to compute the hash of password, using the salt password.
So all the slashes are required to prevent propagate the elements, like the quotes and dollar signs, further down the execution path.
Note that this code isn't actually useful, the crypt is encrypting a constant, I would have assumed that $password
was meant to be passed inside the function call, it doesn't seem useful in the current location.
Also having a script generate a script which calls perl... it doesn't look pretty. I don't know the full context but I find it hard to believe that this is the best way. Personally I would avoid the games and just write a single perl script. My personal rule of thumb is that any bash script that gets complex or goes over 50 lines is done in perl, but that is heavily influenced by the fact that I don't grok or enjoy bash.
Upvotes: 2