Execute remote script with local parameter value
Solution 1
myparameter=foobar
ssh user@server "myscript $myparameter"
This will execute myscript foobar
on the server.
Solution 2
(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"
hello
rm: cannot remove `somefile': No such file or directory
$ ssh user@server "echo $(printf '%q' "$myparameter")"
hello; rm somefile
Solution 3
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")"
Related videos on Youtube
![Emanuel Berg](https://i.stack.imgur.com/tuEbI.jpg?s=256&g=1)
Emanuel Berg
Emanuel Berg Hire me! Programmer, Swedish university degree in Computer Science. computer projects (includes CV, letters, code, screenshots) internet activity (where to find me) Check out some of my Unix & Linux tech writing.
Updated on September 18, 2022Comments
-
Emanuel Berg almost 2 years
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?
-
Emanuel Berg almost 12 yearsSimple as that! Works great. (I had to put a "./" before the script name because otherwise it looked for
~/.elm/aliases
.) -
Tilo Wiklund almost 12 yearsAs 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 thessh
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. -
janmoesen almost 12 yearsNote that if
$myparameter
contains spaces, it will split on the server side. Bash'sprintf
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.