Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

How can I automatize this task?

1) You are at A. 2) You ssh into B. 3) You run a script at B, that needs a parameter known at A.

First, I thought perhaps I could send the value when I opened the connection with ssh. Then, probably simpler, between 1) and 2), scp the entire script to the same location at B (replacing the old one). But still, how do I execute the script at B? (That is, how to automatize that last step. Of course, I could run it manually after ssh.)

Another thought, maybe discard of ssh altogether - I have a web page at B, so could the script somehow be invoked through an "under the hood" web interface?

Or would you do it in an altogether different way?

Also have a look at Run if statement on remote machine –  Ulrich Dangel Jul 15 '12 at 23:42

3 Answers 3

up vote 4 down vote accepted
ssh user@server "myscript $myparameter"

This will execute myscript foobar on the server.

Simple as that! Works great. (I had to put a "./" before the script name because otherwise it looked for ~/.elm/aliases.) –  Emanuel Berg Jul 15 '12 at 23:19
As a small warning, the use of double quotation marks (") as opposed to single ones (') is important here. Using double means that the shell on your local machine will expand the variable, then execute the ssh command. If single ones were to be used the local shell would not touch the command, which is sent on verbatim but is still be expanded in the remote shell. –  Tilo Wiklund Jul 16 '12 at 1:14
Note that if $myparameter contains spaces, it will split on the server side. Bash's printf has a %q format that you could use. I have some example code, but it does not fit here. I'll create a new answer for it. –  janmoesen Jul 16 '12 at 13:17

If it is safe to assume that $myparameter will not contain single quotes (otherwise see here or use the printf '%q' ... solution by janmoesen), you can just put single quotes around $myparameter to avoid the split-on-space problem on the server side.

myparameter="foo \" bar"
#myparameter="foo \" ' bar"

ssh localhost "set -xv; printf '%s\n' myscript '${myparameter}'"
ssh localhost "set -xv; echo $(set -xv; printf '%q' "$myparameter")"

(This is a follow-up to my comment on the accepted answer.)

Note that if $myparameter contains spaces, it will split on the server side. Bash's printf has a %q format that you could use. Example:

$ myparameter='hello; rm somefile'
$ ssh user@server "echo $myparameter"
rm: cannot remove `somefile': No such file or directory

$ ssh user@server "echo $(printf '%q' "$myparameter")"
hello; rm somefile

This site is currently not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .