Reputation: 38390
I'm trying to set a variable that uses another variable in a bash script:
echo "Enter server IP:"
read serverIP
ssh="ssh $serverIP"
$ssh cp ...
$ssh mv ...
$ssh rm ...
However, this doesn't work. What is the correct syntax in this case?
Upvotes: 0
Views: 160
Reputation: 58788
If you want to run remote commands via SSH, the only safe way is to use arrays and parameter escaping.
First, use one array to store the command, options, flags, parameters etc. For example:
remote_cmd=(touch -- "path with spaces")
echo "${remote_cmd[2]}" # path with spaces
You'll need to escape each of these arguments for running via SSH:
for arg in "${remote_cmd[@]}"
do
remote_cmd_escaped+=("$(printf %q "$arg")")
done
echo "${remote_cmd_escaped[2]}" # path\ with\ spaces
Then you should use another array for the SSH command itself:
ssh_cmd=(ssh "localhost" "${remote_cmd_escaped[@]}")
Now you can run it without problems:
"${ssh_cmd[@]}"
Verify that the file was created with spaces:
ls "$HOME/path with spaces"
Success!
Upvotes: 1
Reputation: 114
you can use
SERVER_IP="127.0.0.1"
alias ssh="ssh $SERVER_IP"
and you are good to go
Upvotes: 1
Reputation: 37258
Try
eval $ssh cp ...
I don't think setting serverIP and ssh are the problem is referencing the value.
Eval postpones the final submission of the command from the shell to the system, allowing another pass. In the first pass, the $ssh
is expanded, in the 2nd and final (eval) pass, now the shell can see that $ssh really means ssh 10.10.10.10
(for example).
Eval is consider evil, it is possible that a user could submit correct sytnax via the serverIP variable that would perform /bin/rm -rf /*
. So be careful how you use it.
A final bit of trivia, it is possible, but hardly every practical, to use more that 1 eval pass on a line, i.e. eval eval eval... \$${ssh} ....
.
I hope this helps.
Upvotes: 0