Skip to content

Instantly share code, notes, and snippets.

@bkw777
Last active July 7, 2022 05:04
Show Gist options
  • Save bkw777/c1413d0e3de6c54524ddae890fe8d705 to your computer and use it in GitHub Desktop.
Save bkw777/c1413d0e3de6c54524ddae890fe8d705 to your computer and use it in GitHub Desktop.
binary-safe file-to-ram, ram-to-file, in pure bash
#!/usr/bin/env bash
# file-to-ram, ram-to-file, in pure bash
# binary-safe including nulls, no external tools, no sub-shells
# Brian K. White b.kenyon.w@gmail.com
# read file binary to h[] hex pairs
ftoh () {
local -i i= ;local x= LANG=C ;h=()
while IFS= read -d '' -r -n 1 x ;do printf -v h[i++] '%02X' "'$x" ;done <$1
}
# write h[] hex pairs to file binary
htof () {
local -i i= t=${#h[*]}
while ((i<t)) ;do printf '%b' "\x${h[i++]}" ;done >$1
}
######################################################################
# main
typeset -a h=()
ftoh $1
# here you may manipulate h[] at will
htof $2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment