Shell – How to append multiple lines to a file without last newline

io-redirectionshell-scripttext processing

I have a very long string that is split in chunks. I want to append them to a file without putting the newline character using bash.

Example:
First append

cat >> abc.sh << EOL
echo "bla bla"
ifcon
EOL

Second append

cat >> abc.sh << EOL
fig -a
uname -a
EOL

And the file abc.sh should be:

echo "bla bla"
ifconfig -a
uname -a

and not

echo "bla bla"
ifcon
fig -a
uname -a

How can I achieve this?

Best Answer

<< always includes a trailing newline (except for an empty here document).

You'd need to do either:

printf %s 'echo "bla bla"
ifcon' >> file

Or use a command that removes the trailing newline character instead of cat:

awk '{printf "%s", l $0; l=RT}' << EOF >> file
echo "blah bla"
ifcon
EOF

(Or perl -pe'chomp if eof')

Or, where here-documents are implemented with temporary files (bash, zsh, pdksh, AT&T ksh, Bourne, not mksh, dash nor yash), on GNU/Linux systems, you could do:

{ 
  chmod u+w /dev/stdin && # only needed in bash 5+
    truncate -s-1 /dev/stdin &&
    cat
} << EOF >> file
echo "blah bla"
ifcon
EOF
Related Question