I have two bash scripts main.sh and a util.sh, and I reference utils.sh in the main.sh by using . util.sh. Now I want to run main.sh via ssh. Obviously, this won't work:

ssh user@host "bash /dev/stdin < main.sh"

Because remote shell cannot find util.sh. So how should I do this, without copying util.sh to remote machine ?

  • To run a remote script ssh user@host main.sh would be enough actually. Why can't you just copy util.sh over as well? – nohillside Dec 24 '18 at 9:15
  • Maybe utils.sh is a common module and reused by many scripts – Lewis Chan Dec 24 '18 at 9:31
  • 1
    You still can deploy it to host together with main.sh. Or put it onto a shared/network drive somewhere. Or have main.sh check whether it is available locally and download it from somewhere if not. – nohillside Dec 24 '18 at 9:49

Even though I think deploying util.sh to host would be the better/more stable solution, you could do something like putting this on top of main.sh


cat > "$U"
. "$U"
rm -f "$U"
# rest of script

and then run

ssh user@host main.sh < util.sh

To be more fail-safe you may require some extra coding in main.sh to handle issues with the temp file being unwritable/undeletable, no input passed on stdinetc.


This is ugly, but should work:

ssh user@host bash < <(sed 's/\. util\.sh/ {r util.sh; d}' main.sh)

That will embed the contents of the util script into the main script, and then pipe the script to the bash process running on the remote host. Note that I've removed the double quotes: the process substitution needs to run on your local machine where both files reside.

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.