Skip to content

Instantly share code, notes, and snippets.

@benstiglitz
Created October 30, 2013 18:43
Show Gist options
  • Save benstiglitz/7237812 to your computer and use it in GitHub Desktop.
Save benstiglitz/7237812 to your computer and use it in GitHub Desktop.
Today’s bad shell script idea: netstrings.
#!/bin/bash
encode() {
local data
OLDIFS="${IFS}"; IFS=""
read -d "" data
IFS="${OLDIFS}"
echo -n $(echo -n "$data" | wc -c)
echo -n ":$data"
echo -n ","
}
decode() {
local data net_count terminator
read -d : net_count
OLDIFS="${IFS}"; IFS=""
if [ ! "${net_count}" == "0" ] ; then
read -d "" -n "${net_count}" data
fi
read -d "" -n 1 terminator
IFS="${OLDIFS}"
if [ ! "$terminator" == "," ] ; then
echo "Invalid netstring terminator ${terminator}"
exit 1
fi
echo -n "${data}"
}
run_tests() {
( echo -n "Looks like this is:" | encode ;
echo -n "" | encode ;
echo -ne "\nworking.\n" | encode ) |
( decode ; decode; decode )
}
if [ "$(basename $0)" == "netstring.sh" ] ; then
run_tests
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment