hjfitz
hjfitz

Reputation: 419

Weird cat behaviour

inside of a function, I would have had multiple echos, but I remembered I could do cat << EOF followed by my text to output, followed by EOF. However, it only seems to work when the EOF part is not indented, like this

init(){
    if [ conditionial ]; then
        cat << EOF
        this is some text
        this is more text
        this is even more text

EOF

but it doesn't work like this:

init(){ if [ conditionial ]; then cat << EOF this is some text this is more text this is even more text EOF

Any ideas?

Upvotes: 1

Views: 96

Answers (3)

torek
torek

Reputation: 489173

"Here document" terminators must appear at the beginning of the line, unless the redirection operator has a - suffix:

cat << END
this does not
  END
here, but rather here
END

vs:

cat <<- END
this one does end here
        END

(watch out for spaces vs tabs; and some older shell variants do not support this).

Besides these, another useful trick is the handling of expansions inside here documents. If the end word (END in my examples above, EOF in yours) is quoted, expansion is inhibited:

cat << E1
you are in a maze of twisty little directories: $PWD
E1
cat << 'E2'
you owe the Usenet Oracle $1.75 for the Tab.
E2

Upvotes: 2

Tiago Lopo
Tiago Lopo

Reputation: 7959

The EOF has to in the beginning of the line and It cant't have anything after it but end of line:

#! /bin/bash
function say_hello {
        cat << EOF
        hello
        world
EOF
} 

Execution:

bash test.sh
        hello
        world

Taking a closer look with cat -A:

cat -A  test.sh
#! /bin/bash$
$
function say_hello {$
^Icat << EOF$
^Ihello$
^Iworld$
EOF$
}$
$
say_hello$

I had problem with script which would have space after EOF and would not work, only with cat -A I could identify the space.

Upvotes: 0

e.dan
e.dan

Reputation: 7497

I never knew this till you asked, but you can use <<- (note the -) to ignore leading tabs (not spaces).

See here

Upvotes: 0

Related Questions