top | item 29796002

(no title)

pdkl95 | 4 years ago

Regarding the creation and removal of a tempfile (line 72 & 85):

    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.

discuss

order

dzove855|4 years ago

I always use mktemp and trap to remove tmp files.

But in this script i would like to avoid external commands. I will even remove the use of tmp files kn thw future.

goombacloud|4 years ago

To spare you the trap you can open the file as FD in your bash process (e.g., exec {my_fd}>"$TMPFILE") and then directly delete it before doing anything else, and use the /proc handle to access it ("/proc/$$/fd/${my_fd}")

mmmooo|4 years ago

can use $RANDOM to get more entropy/avoid collisions, though as you said, better not to use files at all.