2

So am creating a bash script that uses the usermod --password command to set user password on remote servers. I have successfully used the openssl passwd -1 command to encrypt my password and I have stored them in an environment variable as follows:

export $MYPASS=$(openssl passwd -l easypass)

Now when I echo my variable, it looks good! but when I use in the script, the password is not working, it turns out that the dollar sign in expanded when I ssh into the remote host .. How Can i stop this from happening?

SO locally it works amazing

echo $MYPASS
$1$bNs852RL$oFd5/p4jCV6TuDdEJprNZ0

Check what happens when I ssh:

 ssh webserver1 "echo $MYPASS"
/p4jCV6TuDdEJprNZ0

Any hints will be greatly appreciated. One very dumb way to fix it will be putting escape character before every dollar sign but I feel there is a better way ... thank you.

aboria
  • 123
  • 6
  • 2
    Does this answer your question? [Difference between single and double quotes in Bash](https://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash) – Jetchisel Jul 12 '21 at 22:22
  • @Jetchisel no it didn't ..... I know the differences between single and double quotes .. my question is more advanced .. am talking about a specific scenario here -- remote hosts. if i do single quotes, I won't be able to even get my variable value all together – aboria Jul 12 '21 at 22:43
  • Variable assignment the `$` is not allowed on the left hand side. Not sure if `export` expands/accepts it... – Jetchisel Jul 12 '21 at 22:51
  • 2
    `ssh webserver1 "echo '$MYPASS'"` – jhnc Jul 12 '21 at 23:27

2 Answers2

3

The problem is that your command is evaluated twice: once to run in your local shell, and once again when executed on the remote host. You therefore need to escape the result of the expansion.

Fortunately, bash4+ makes this easy with the @Q quote modifier:

var="tricky value with space, \\, \$s, 's and \"s"
ssh localhost "echo ${var@Q}"
that other guy
  • 116,971
  • 11
  • 170
  • 194
0

using an escape quote is a simpler way but another way is, to use a single quote before and after your $MYPASS variable, then you can run tr -d "'" to remove the single quote after, if you need to before using the environment variable.

Shaqil Ismail
  • 1,794
  • 1
  • 4
  • 5