Skip to content

Instantly share code, notes, and snippets.

@lukjod
Forked from chanibal/README.md
Last active September 25, 2019 09:25
Show Gist options
  • Save lukjod/d085863e6804e3839c5d234bcc58d3fc to your computer and use it in GitHub Desktop.
Save lukjod/d085863e6804e3839c5d234bcc58d3fc to your computer and use it in GitHub Desktop.
An utility to add BOM to UTF-8 files
#!/usr/bin/env bash
set -e
if [[ $# == 1 ]]; then
INPUT="$1"
OUTPUT="$(mktemp)"
SUCCESS=0
function commit
{
if [[ "$SUCCESS" == "1" ]]; then
mv "$OUTPUT" "$INPUT"
fi
rm -f "$OUTPUT"
}
trap commit EXIT
FAIL_IF_OUTPUT_EXISTS=0
elif [[ $# == 2 ]]; then
INPUT="$1"
OUTPUT="$2"
FAIL_IF_OUTPUT_EXISTS=1
else
cat << ENDSYNTAX
Adds a byte order mark to a file and converts to UTF-8
https://gist.github.com/chanibal/397c39d59ede8682ce13
Syntax:
addbom file_to_add_byte_order_mark
addbom input_file output_file
ENDSYNTAX
exit 0
fi
if [[ ! -e "$INPUT" ]]; then
echo "Error: no file: $INPUT"
exit 1;
fi
read -n 3 MAGIC <"$OUTPUT"
if [[ "$MAGIC" == $(echo -ne '\xEF\xBB\xBF') ]]; then
echo "Error: $OUTPUT already has bom"
exit 2
fi
(echo -ne '\xEF\xBB\xBF' && iconv -t utf-32 | iconv -f utf-32 -t utf-8) <"$INPUT" >"$OUTPUT"
SUCCESS=1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment