Gary Sieling

Bash – echo text and file contents

Sometimes it’s useful to be able prepend or append text to a file within a bash script (e.g. if you’re piping it to something else).

Typically you might use ‘cat’ or ‘echo’ but these are the wrong tool for this.

One option is to do this:

printf '%b\n%b' 'SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY;\n' "$(cat test.sql)"

A better option is this:

sed 1s/^/"stuff to insert"\n/

The advantage of this is you can avoid byte order mark errors – the printf will leave the the BOM in the middle of the file and you’ll get this (at least with psql – it only strips the BOM if it’s at the beginning of the file):

ERROR:  syntax error at or near ""
LINE 1: 
Exit mobile version