0

I have a script which writes some content into a file with cat and EOF. While this thing works within a bash script, it doesn't work if I put it inside a function.

Working code:

cat << EOF | sudo tee /etc/network/interfaces
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet dhcp
EOF

It's syntax highlighting (which seems fine);

enter image description here

Not working code:

function someFunctions {
    cat << EOF | sudo tee /etc/network/interfaces
    auto lo
    iface lo inet loopback

    auto eth0
    iface eth0 inet dhcp
    EOF
}

someFunctions

This one's syntax highlighting (which doesn't seem fine);

enter image description here

My editor (Atom) shows everything as green, which means it loses it's syntax highlighting but I couldn't find what's wrong.

How can I fix this?

  • Is the syntax highlighting the only indication that something is wrong? The function works AFAICT, so the problem does not seem to be with bash. If that is the case, I would complain to the Atom people. – NickD Mar 8 at 18:23
  • As I've stated, the script is not working as well so it's not about syntax highlighting. I just showed that cuz I thought maybe it would mean something. – Marry Jane Mar 8 at 18:25
4

The EOF here-doc marker must either be at the beginning of the line, or a full TAB character indented:

someFunctions {
        sudo tee /etc/network/interfaces <<-'EOF'
        auto lo
        iface lo inet loopback

        auto eth0
        iface eth0 inet dhcp
        EOF
}

I've removed the function keyword as it's deprecated, and the cat as it adds no value. I've also used <<-'EOF' (instead of <<EOF) so that leading TAB characters are stripped, and the content of the here-doc is not evaluated for variables and other substitutions. If you want variable substitution don't quote the EOF, and use <<-EOF instead.

  • Thanks @roaima, this definitely works. But it doesn't support variables tho. Is there way to add variable support to this? – Marry Jane Mar 8 at 18:36

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.