Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running local script remotely with shell script here documents

Tags:

bash

shell

unix

ssh

I need to run a script remotely. I am using the following shell script

    for server in $servers
     do
     LOCAL_VAR=<some_value>
     ssh $server <<EOF
      command1 $LOCAL_VAR
      command2..
      ..
      exit
      EOF
    done

bash shows unexpected end of file syntax error. The rest of the code works fine if I remove this block. Can you please tell me the correct way of executing a script remotely.

like image 257
Pradeep Jawahar Avatar asked May 20 '26 13:05

Pradeep Jawahar


2 Answers

If you want to put indentation like that in your here-doc, you should add a - like the following code :

for server in $servers
do
    LOCAL_VAR=<some_value>
    ssh $server <<-EOF
    command1 $LOCAL_VAR
    command2..
    ..
    exit
    EOF
done

Take care when you copy paste this, sometimes you can have surprises with tabs or spaces.

like image 74
Gilles Quenot Avatar answered May 23 '26 13:05

Gilles Quenot


Your EOF to close the heredoc must not have any leading spaces. Bash does not think it has reached the end of your string before finding the end of the script.

http://tldp.org/LDP/abs/html/here-docs.html

The closing limit string, on the final line of a here document, must start in the first character position. There can be no leading whitespace. Trailing whitespace after the limit string likewise causes unexpected behavior. The whitespace prevents the limit string from being recognized.

like image 34
jimp Avatar answered May 23 '26 12:05

jimp