-
-
Save lukjod/d085863e6804e3839c5d234bcc58d3fc to your computer and use it in GitHub Desktop.
An utility to add BOM to UTF-8 files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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