Zi Hao Yan
Zi Hao Yan

Reputation: 1

printf on console vs sh script

I am using a printf command to add some bytes on my file so that it acts like a Byte-Order-Mark.

the following is my SH script

title: add_bom.sh

FILE=$1
printf '\xFF\xFE' >> $1

On my PuTTY terminal, when I do directly

printf '\xFF\xFE' >> test.xls

the result is correct as expected and xxd test.xls displays ff and fe at the first line

However, when I run it via SH

sh  add_bom.sh test.xls

the result is wrong and \xFF\xFE appears at the end of test.xls file as a text

Why it this so?

Upvotes: 0

Views: 256

Answers (1)

tripleee
tripleee

Reputation: 189679

The >> redirection operator always appends to the end of the file.

If you want to prepend, try something like

printf '\xff\xfe' >temp
cat otherfile >>temp
mv temp otherfile

However, adding an UTF-16 BOM to a file which is not a UTF-16 text file in the first place is almost certainly an error.

Upvotes: 3

Related Questions