aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDylan Araps <dylan.araps@gmail.com>2026-03-01 10:47:57 +0200
committerDylan Araps <dylan.araps@gmail.com>2026-03-01 10:47:57 +0200
commit6eb8afe388579511a248a4430271e502c528f071 (patch)
treec195b314ca2c7d4479e80e9b50b863ca281f5b30
parent047718235df457cae482eb0f92b06697964f37a6 (diff)
bin/embed: make /really/ portable
Turns out that sed and awk backslash handling differs across implementations so the original code (and the many other incantations of it I tried) didnt work on macOS and BSD (or worked there but not in GNU or busybox). Here's a POSIX shell version that should work everywhere.
-rwxr-xr-xbin/embed25
1 files changed, 17 insertions, 8 deletions
diff --git a/bin/embed b/bin/embed
index 5efe6d8..40dc853 100755
--- a/bin/embed
+++ b/bin/embed
@@ -1,6 +1,6 @@
-#!/bin/sed -f
+#!/bin/sh -euf
#
-# Convert input to 32bit hex encoded utf8.
+# Escape shell script for embedding in C string literal.
#
# Copyright (c) 2026 Dylan Araps
#
@@ -23,10 +23,19 @@
# SOFTWARE.
#
-/^[[:space:]]*#/d
-s/\\/\\\\/g
-s/"/\\"/g
-s/$/\\n/
-s/^/"/
-s/$/"/
+s() {
+ x=$l
+ shift 1
+ while :; do case $x-$# in
+ *"$1"*) x=${x%"$1"*}$2${x##*"$1"} ;;
+ *-2) break ;;
+ *) shift 2
+ esac done
+}
+
+while IFS= read -r l; do case $l in [!#]*)
+ s "$l" \" "__EMBED_$$_QUOTE__" \\ "__EMBED_$$_SLASH__" \
+ "__EMBED_$$_QUOTE__" \\\" "__EMBED_$$_SLASH__" \\\\
+ echo "\"$x\\n\""
+esac done < "$1"