0

I'm ssh-in to a remote machine (ubuntu) and trying to execute a little script in there.The script looks like this:

myfunction()
{
  input=$1
  count=$2
    ssh ubuntu@ip <<EOF
    if [ $input = "comment" ];then
      TotalCount=$count
      echo "TotalCount is $TotalCount"
    else
      echo "do something"
    fi    
EOF
}
myfunction comment 2

It SSH in to the server but prints empty

Output: TotalCount is

I tried to escape the variable(TotalCount=\$count) since this is running on remote host. But didn't work

  • I don't understand what you're trying to accomplish. The input and count variables are local, but you ware trying to print them remotely ? – glenn jackman Mar 25 at 21:13
  • 2
    $TotalCount will be expanded (to nothing) on the local machine, like all the other variables from the here-document ($input, $count). It's $TotalCount that you should escape TotalCount is \$TotalCount. – mosvy Mar 25 at 21:20
  • What makes you think that the if fails (as stated in the title)? – Kusalananda Mar 25 at 21:49
  • @glennjackman Once I get the TotalCount, my script is going to execute some other commands on the remote server based on TotalCount. I'm not only just trying to print remotely – Nani Mar 25 at 22:35
3

Solution

Try this instead:

myfunction()
{
  input=$1
  count=$2
    ssh user@host <<EOF
    if [ $input = "comment" ];then
      TotalCount=$count
      echo "TotalCount is \$TotalCount"
    else
      echo "do something"
    fi    
EOF
}
myfunction comment 2

Notice that I added a backslash to \$TotalCount to prevent it from being expanded locally.

Explanation

You want to escape the TotalCount variable, because that variable is being defined remotely. If $TotalCount is evaluated locally, then it will (probably) evaluate to the empty string, which explains why you weren't seeing any output. The count variable, on the other hand, is being defined locally, so you don't want to escape it.

  • 1
    @Kusalananda Explanation added. – igal Mar 25 at 21:54

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.