2

I'm trying to execute a script in the remote machine using ssh. I'm using the below command,

ssh -i <remote pem> <user name>@<ip> "sh <full path of script in remote> <parameter>"

In the script referred by <full path of script in remote>, I'm referring to another file as . ./config.sh. Where the config.sh is a sibling of the remote script that I'm trying to execute. But I'm getting the below error.

+ . ./config.sh
<full path of script in remote>: 4: .: Can't open ./config.sh

When the config.sh is available as a sibling for the script that I'm trying to execute with requrired rights, why am I getting this error? How to get around this?

4

Your remote shell command will by default execute in the user's $HOME as working directory. If you're giving the full path to the script to execute, that will of course properly launch the remote script, but that script's working directory will still be the user's home. Hence, as config.sh is only a relative file reference, and since it not in the working directory, you cannot source it.

You have several options for solving that:

  1. Before calling the remote script in the sh shell, cd into the directory where it is stored:

    ssh  <username>@<ip> "cd /path/to/script; sh <script name> <parameter>"
    
  2. If you can change the remote script, inside the script, at the beginning, cd to its own path so that your working directory changes for all future calls within that script. The working directory of your shell (from which you call the script) will not change if you execute the script with sh.

  3. In the script, call config.sh by its absolute path, e.g. source /path/to/config.sh instead of source config.sh. However, that will not be very portable. Or, better:
  4. In the script, call config.sh with reference to the current script, e.g. source "$(dirname "$0")/config.sh"

Generally, when scripting, you should try to avoid making relative references if you cannot be sure that the script itself is called from the right working directory. For example, what if a script includes a rm -rf <relative path> statement, but you execute it from the wrong working directory? It could irrevocably delete the wrong data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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