1

I am trying to pass a variable in a bash script to sshpass. Here is my code for reference:

NAME="HARRY"
sshpass -p passwd ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -q ipaddress 'bash -s' << 'EOF'
   echo $NAME
EOF

How can I pass the variable in a bash script to sshpass? Thank you!

3
  • Does this answer your question? Passing variable into sshpass command inside a script for loop Commented Aug 6, 2021 at 14:14
  • Public-key authentication would let you get rid of sshpass, making your script much simpler. Commented Aug 6, 2021 at 14:17
  • Agreed, sshpass isn't the most secure way. Also, if you repeat ssh conntections to the same server, consider adding a controlmaster with ssh option -o ControlMaster=auto -o ControlPersist=yes -o ControlPath=/var/run/ctrlm.%r@%h so you keep a persistent ssh connection for some time. This way next time you launch ssh, it keeps the already open connection from last time. By default, controlmasters are open 1H. Commented Aug 6, 2021 at 14:39

3 Answers 3

0

Easiest way is using env just before running bash

NAME="HARRY"
sshpass -p passwd ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -q ipaddress env NAME="$NAME" 'bash -s' << 'EOF'
   echo $NAME
EOF

You can pass multiple variables with multiple env statements like

export NAME="HARRY"
export SOMEVAR="hello"
sshpass -p passwd ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -q ipaddress env NAME="$NAME" env SOMEVAR="$SOMEVAR" 'bash -s' << 'EOF'
   echo $NAME
EOF

Be aware that your variables might be interpreted when passing them. You can avoid that by changing env NAME="$NAME" to uninterpreted version env NAME="'$NAME'"

Sign up to request clarification or add additional context in comments.

2 Comments

This can cause its own problems, because now ssh has to combine env and all its arguments into a single string.
Indeed, best solution I found so far is singlequoting the variable in doublequotes to avoid unwanted interpetation.
0

You can simply put a dollarsign in front of the variable name, as in this example:

Linux Prompt>cat test.txt
<here you see file content>
Linux Prompt>filename=test.txt
Linux Prompt>cat $filename
<here you see file content>

Comments

-1

Put it after the -p option:

password=YourPassword
sshpass -p "$password" ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -q ipaddress 'bash -s' <<EOF
    echo "$NAME"
EOF

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.