by pdkl95 · 4y ago · 0 comments
local tmpFile="${TMPDIR:-/tmp/bash-web-server.$$}"
# ...
rm "$tmpFile"
To avoid collisions when the PID is reused, and to clean up0 the tempfile on errors, I recommend using mktemp and trap: local tmpfile="$(mktemp --tmpdir="${TMPDIR:-/tmp}" bash-web-server.XXXXXX)"
trap "rm -f \"${tmpfile}\"" RETURN EXIT
# ...
# Do nothing at the end of the function; trap will
# remove the file at RETURN automatically.
Otherwise, I like the implementation! It's nice to see good bash techniques like parsing with "IFS='&' read -ra data" and rewriting variables with %%/etc.But in this script i would like to avoid external commands. I will even remove the use of tmp files kn thw future.
true | sleep infinity &
STDINPID="$!"
TMPPIPE="/proc/$STDINPID/fd/0"
echo hello > "$TMPPIPE"
echo write more > "$TMPPIPE"
cat "$TMPPIPE"
echo write again > "$TMPPIPE"
cat "$TMPPIPE"
kill -9 "$STDINPID" # clean up pipe
Now I would like to avoid the additional process by using the current shell process instead. true | sleep infinity &
STDINPID="$!"
exec {mypipe}<"/proc/$STDINPID/fd/0" # hijack FD
TMPPIPE="/proc/$$/fd/${mypipe}"
disown "$STDINPID" # suppress killed message on stderr
kill -9 "$STDINPID" # clean up process now already
echo hello > "$TMPPIPE"
echo write more > "$TMPPIPE"
cat "$TMPPIPE"
echo write again > "$TMPPIPE"
cat "$TMPPIPE"