Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to run a program on a machine that I have ssh access to from a gateway machine that I can access with ssh too.

When I want to run an mpi program on the target machine T, I access to the gateway G from my local machine the usual way :

ssh user@Gateway

Once on the G machine, I start my program on the target machine like this :

ssh Target 'eval $(ssh-agent -s);ssh-add my_key;mpirun --hostfile .hosts program'

This way everything works correctly (notice that I need ssh-agent and ssh-add to run before mpirun, refer to this question for details.)

I want to pass the second ssh command directly to the ssh command on my local machine when I access the Gateway, something like this

ssh user@Gateway "ssh Target 'eval $(ssh-agent -s);ssh-add my_key;mpirun --hostfile .hosts program'"

But this doesn't work, because of the " I think.

PS: I cannot use ssh-agent-forwarding.

share|improve this question
up vote 2 down vote accepted

You have the escape the $. Otherwise $(ssh-agent -s) will get evaluated on your local machine instead of the gateway machine.

ssh user@Gateway "ssh Target 'eval \$(ssh-agent -s);ssh-add my_key;mpirun --hostfile .hosts program'"

You can verify the results of escaping by using echo

$ echo "foo $(echo bar)"
foo bar
$ echo "foo \$(echo bar)"
foo $(echo bar)
share|improve this answer

Your command evaluates $(ssh-agent -s) on the local machine, since it's between double quotes. You need to put the whole command to run on the gateway between single quotes. Since that command itself contains single quotes (to protect code that's supposed to be run on the target), you need to escape those single quotes as '\''.

ssh user@Gateway 'ssh Target '\''eval $(ssh-agent -s); ssh-add my_key; mpirun --hostfile .hosts program'\'

You can automate the gateway step by configuring your local ssh client. Put this in your ~/.ssh/config:

Host Target
User user
ProxyCommand ssh Gateway nc %h %p

nc is netcat. Then run

ssh Target 'eval $(ssh-agent -s);ssh-add my_key;mpirun --hostfile .hosts program'

directly from the local machine.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.