How to set heredoc output to local variable

7,358

You need to quote the EOF marker, eg <<\EOF or <<'EOF' to stop your $filename variable from being evaluated before it is passed to the remote. You can see the effect with say /bin/bash -v instead of /bin/bash.

I also needed to have the actual EOF marker on a line of its own, with the final ) on the next line.

Share:
7,358

Related videos on Youtube

Jokas
Author by

Jokas

Updated on September 18, 2022

Comments

  • Jokas
    Jokas over 1 year

    I'm trying in a heredoc to set its output to a local variable as follows :

    REMOTE_OUTPUT=$(ssh remote@server /bin/bash << EOF
      find my/path/ -type f -not -path my/path/*/ -type f -mtime -0 | while read filename; do
            if grep "ERROR" $filename; then
                filenamebase=$(basename "$filename")
                echo -e "\n----------------------------------------------------------\n\n$filenamebase failure:\n"
                grep -n "ERROR" "$filename" | sed G
            fi
        done
    EOF)
    

    But the variable stays null even though the find&grep loop is correct and should indeed return an output.

    (Otherwise I would also be interested in writing the output of the heredoc into a local file.)

    • RobertL
      RobertL over 8 years
      What's that mean: "find&grep loop is correct"? How do you know?
    • Jokas
      Jokas over 8 years
      I mean I have tried it locally to check that the output is not empty (same folders and files in the local and remote servers)
    • RobertL
      RobertL over 8 years
      Did you try with ssh, but without the command substitution REMOTE_OUTPUT=$( )?
    • Jokas
      Jokas over 8 years
      Yes it works fine but I need to store the output to append it to a file whose content will be sent in a mail
    • Jokas
      Jokas over 8 years
      Nothing is append to the file
    • Dmitry Grigoryev
      Dmitry Grigoryev over 8 years
      What happens if you run your command with here-doc but without command substitution? Also, have you tried to run ssh with -T option?
    • RobertL
      RobertL over 8 years
      Did the command go back to the prompt or did you have to interrupt it with control-C?
    • Jokas
      Jokas over 8 years
      Meuh found the solution below :)
    • RobertL
      RobertL over 8 years
      Did you try the >somefile without the $()?
    • RobertL
      RobertL over 8 years
      Did you delete the ssh too?
    • RobertL
      RobertL over 8 years
      Did you try everything in the answer below?
  • RobertL
    RobertL over 8 years
    I think the problem is the EOF) because questioner said the command worked without the command substitution $().
  • Jokas
    Jokas over 8 years
    I've done it, it is it that solved my issue :)