Redirect content under a new line (without further syntax or arguments)

cathere-stringio-redirectionnewlinestext processing

I tried these ways to append content to a file:

printf "\nsource ~/script.sh" >> /etc/bash.bashrc
echo -e "\nsource ~/script.sh" >> /etc/bash.bashrc
cat >> "/etc/bash.bashrc" <<< "source ~/script.sh"

All three ways work. I find the cat herestring less comfortable as one needs to read it from the end (after cat append this[end] to[start]).

All way don't automatically break the line and the \n syntax for printf and echo is one I'd personally use as last resort. Moreover, I don't know of any way to add a newline for an herestring, and found no such way in this documentation.

What I seek is a utility that goes down one line automatically without the need to add any argument or syntax. I tried to read on nix text processing utilities, but found nothing like what I seek. Do you know such a utility?

Best Answer

You don't need to write the cat line "the wrong way", this works just fine (though of course the arrows in the here-string still point in an odd direction):

$ cat <<< "some text" >> testfile
$ cat testfile
some text

As mentioned in the comments, the here-string adds a newline at the end, while with printf and echo you used \n in the front of the string. echo would usually add the tailing newline, just like the here-string, so if you need just that, echo should be fine (plus it's a builtin in most shells.)

All your commands work slightly differently with the newlines

cat >> file <<< "string"        # newline at end
printf "\nstring" >> file       # newline at beginning
echo -e "\nstring" >> file      # newline at beginning and at the end

Frankly, I think it's better to get used to the \n notation, but if you don't like it, there's always here-docs (both leading and tailing newlines here):

cat >> file <<EOF

some text
EOF
Related Question