Passing a variable to a remote host in a bash script with ssh and EOF [duplicate]
I have a script parsing a list of servers, looking for some stuff and executing commands if the circumstances are correct. The main server is connecting to them via ssh, executing all commands that are in the EOF statement:
#!/bin/bash
# parsing servers
# defining one local variable $VAR
ssh -T -p 1234 root@"server-ip" "$variable" << 'EOF'
# doing some stuff...
var_result=$(mysql -hhost -uuser '-ppasswort' -Ddatabase -N -e "SELECT something FROM somewhere WHERE value=$VAR;")
EOF
I know the variable can pass through if I remove the single quotes from the EOF, but if i do so the mysql statements wont work and everything breaks.
I know there are ways to transmit a variable, but things with ";" between options wont work for me ( the script tries to execute it as a command )
Any ideas?
Use printf %q
to escape content in an eval
-safe form; after doing so, you can pass them on the command line of the remote shell, and retrieve them via $1
, $2
, etc. within the remote script:
# put contents of $VAR into $var_str in a format that a shell can interpret
printf -v var_str %q "$VAR"
# v- pass the value on the shell command line
# | v- keep escaping the heredoc securely
# | |
ssh -T -p 1234 root@"$host" "bash -s $var_str" <<'EOF'
# retrieve it off the shell command line
var=$1
# ...and use it as you like thereafter.
echo "Remotely using $var"
EOF
How about using EOF
without the quote and making the mysql
command work:
#!/bin/bash
# parsing servers
# defining one local variable $VAR
VAR=something
ssh -T -p 1234 root@"server-ip" <<EOF
# doing some stuff...
var_result=\$(mysql -hhost -uuser '-ppasswort' -Ddatabase -N -e "SELECT something FROM somewhere WHERE value=$VAR;")
EOF
As Charles Duffy stated, this may produce some security risk.
Another way is to wrap all your codes around single quote:
#!/bin/bash
# parsing servers
# defining one local variable $VAR
ssh -T -p 1234 root@"server-ip" '
# doing some stuff...
var_result=$(mysql -hhost -uuser "-ppasswort" -Ddatabase -N -e "SELECT something FROM somewhere WHERE value='"$VAR"';")
'
In this case you will have to be careful what you substitute your variables for. Better use Charles Duffys' method if you should be concerned about it.