Adding utf-8 Byte Order Mark to file

#!/bin/bash
# add_bom.sh

FILE=$1

check() {
  if (( e = "$1" )); then
    echo "ERROR: $ACTION failed!!"
    exit $e
  else
    echo "INFO: $ACTION Success!!"
  fi
}

set_bom() {
    ACTION="Setting utf-8 BOM"
    # Detect if BOM already exists
    BOM=`sed -n '1{/^\xEF\xBB\xBF/p}' $FILE`
    if [ -z $BOM ]; then
        [ -f "$FILE" ] && /usr/bin/vim -e -s +"set bomb|set encoding=utf-8|wq" $FILE
        check $?
    fi
}

set_bom

To run, give the script the file name as argument:

sh ./add_bom.sh /path/to/file

Test the file via xxd, if the mark is present, the first line should output as below:

$ xxd </path/to/file
0000000: efbb bf...

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Reinventing

There's a builtin in vim - :set bomb

Comment