Shell – Executing commands with ssh and shell script using variables on a remote machine

remoteshell-scriptsshvariable substitution

I'd like to execute a command and script located on a remote machine with a script on a local machine. I know it's possible to execute these kind of commands with ssh, so I made:

#!/bin/bash
ssh username@target 'cd locationOf/theScript/; ./myScript.sh'

It works perfectly.
I'd like this script to be more generic, using variables. Now, it is:

#!/bin/bash
LOCATION=locationOf/theScript/
EXEC=myScript.sh
ssh username@target 'cd ${LOCATION}; ./${EXEC}'

And I get this error: bash: ./: is a directory

I guess the remote machine doesn't know these variables. So is there a way to export them to the target ?

Best Answer

I don't know an easy way of exporting environmental variables to target, but your script might work if you replace ' with ". With 's the string 'cd ${LOCATION}; ./${EXEC}' gets passed verbatim, but with

ssh username@target "cd ${LOCATION}; ./${EXEC}"

variable substitution is done locally.

Note that the values of LOCATION and EXEC are passed to the remote shell, so this only works if they don't contain any shell special characters.

Related Question