How to append multiple lines to a file without last newline?

8,828

Solution 1

<< 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

Solution 2

Use echo with the -n switch:

 echo -n "blah blah" >> file
Share:
8,828

Related videos on Youtube

Admin
Author by

Admin

Updated on September 18, 2022

Comments

  • Admin
    Admin over 1 year

    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?