0

Wanted to create a directory in my remote server by executing the script from my local, expected directory is not getting created on the remote VM and no error message is given as well.

I tried to escape the variable using \, enclosed the variable in single as well as in double quotes, but of no luck..

What am I missing ?

#!/bin/bash

password="mypassword"
remote_ip="10.28.28.28"
dir_to_create="/home/rocket/DjangoDir"


sshpass -p ${password} ssh -q -tt user@${remote_ip} << 'EOT'
    mkdir -p \$dir_to_create
  exit
EOT

Also, tried "\$dir_to_create" , \"$dir_to_create" and \"${dir_to_create}"

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Rookie1999
  • 111
  • 1
  • 8
  • https://stackoverflow.com/questions/305035/how-to-use-ssh-to-run-a-local-shell-script-on-a-remote-machine – KamilCuk Feb 07 '21 at 09:37
  • variables defined in the local script do not exist on the remote system. Why are you quoting them? Might they contain spaces or special characters? – stark Feb 07 '21 at 12:21

1 Answers1

2

Variables expansions are not executed in a here document with quoted delimiter. Use unquoted delimiter to allow expansions to happen.

Because the remote shell re-parses the expression, remember about properly quoting the variables. The remote may not execute shell on the remote side - explicitly execute your shell and read from stdin. Remember to quote variable expansions:

ssh "user@${remote_ip}" 'bash -s' <<EOT
mkdir -p $(printf "%q" "$dir_to_create")
EOT

Properly passing properly quoted variables is a hard job. Do not do it yourself - use bash features. For me the best stable and simple to use feature for to transfer locally defined work to remote context is to use a function:

func() {
    mkdir -p "$dir_to_create"
}
ssh "user@${remote_ip}" 'bash -s' <<EOT
$(declare -p dir_to_create) # transfer variables values
$(declare -f func)          # transfer function definition
func                        # call the function
EOT

Please research: quoting in shell - what to use, what does it mean, what it's effect is. Research declare - what does it do. Research here document - how does a quoted terminating word <<'EOT' differ from unquoted one <<EOT. Check your scripts with http://shellcheck.net .

KamilCuk
  • 120,984
  • 8
  • 59
  • 111