Blank space cause error when use perl

I write a script with register and login user.
So, i encrypt password with
encryptedpass=`perl -e "print crypt("${mypass}",salt)"`

if password do not contain blank space, it work
but if password have blank space, it cause error in that line

the error is:
syntax error at -e .....

Anyone have solution? Or face this before, how to solve this?
Thank you.

It's the quoting. If you run that part with tracing enabled (set -x), it will look something like this:

> set -x
> export mypass=1234
+ export mypass=1234
+ mypass=1234
> encryptedpass=`perl -e "print crypt("${mypass}",salt)"`
++ perl -e 'print crypt(1234,salt)'
+ encryptedpass=saS3eimg8Mg1M
> export mypass="1234 5678"
+ export 'mypass=1234 5678'
+ mypass='1234 5678'
> encryptedpass=`perl -e "print crypt("${mypass}",salt)"`
++ perl -e 'print crypt(1234' '5678,salt)'
syntax error at -e line 1, at EOF
Execution of -e aborted due to compilation errors.
+ encryptedpass=
>

As you can see, in the second example Perl gets passed 3 options (-e, 'print crypt(1234', and '5678,salt)' ) which in this case in invalid. One of those changes should work:

encryptedpass=`perl -e "print crypt(\"${mypass}\",salt)"`
encryptedpass=`perl -e "print crypt('${mypass}',salt)"`

The first has variable substitution enabled for both the shell and Perl, but is a bit less readable. The second disables substitution within Perl, but has better readability. In the end it's a question of style.

It worked after i made change follow your post
Thank you so much

in my case, i can't use

'${mypass}'

because it will understand ${mypass} as a string not a variable
so the first is better (in my case).

Thank you again. :slight_smile:

Yes, you can, because the outermost quotes are relevant to the shell in this case. Example:

> set -x
> export mypass=1234
+ export mypass=1234
+ mypass=1234
> encryptedpass=`perl -e "print crypt(\"${mypass}\",salt)"`
++ perl -e 'print crypt("1234",salt)'
+ encryptedpass=saS3eimg8Mg1M
> encryptedpass=`perl -e "print crypt('${mypass}',salt)"`
++ perl -e 'print crypt('\''1234'\'',salt)'
+ encryptedpass=saS3eimg8Mg1M
>

The only difference are the quotes passed to Perl, at which point the variable is already substituted. It would only make a difference with variables that you defined within the Perl command that the shell has no knowledge of.