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

Post new comment

  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.
Comment