0

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?

4
  • What is the error or behavior? do an echo $ssh. Commented May 24, 2012 at 3:33
  • It just outputs ssh. It doesn't have the IP I entered. Commented May 24, 2012 at 3:37
  • Your assignment should work fine. It's the execution of the variable as a command that's the problem. Please see BashFAQ/050. Why do you need to have the command in a variable? Commented May 24, 2012 at 3:50
  • Dennis: to repeat it multiple times without having to type it in multiple times (like in the last 3 lines of my code example). Commented May 24, 2012 at 4:32

3 Answers 3

1

you can use

SERVER_IP="127.0.0.1"
alias ssh="ssh $SERVER_IP"

and you are good to go

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

2 Comments

This doesn't seem to output the IP I entered. If I do an echo ssh, only ssh is outputted.
@DanielT. Try echo $ssh with a $
1

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!

Comments

0

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.

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.