Skip to content
Tavis Ormandy edited this page Mar 13, 2019 · 3 revisions

Common questions and notes about using halfempty.

Q. My script works when I test it using redirection, but halfempty says it doesn't work.

Halfempty sends input to your script using pipes, this usually works fine because most applications just want to read the input using read(). However, some applications want to use operations like lseek() that simply won't work on pipes.

When you test your script with redirection, e.g. testscript.sh < testinput, stdin is attached to a file and it is possible to lseek(STDIN_FILENO, ...). To closer replicate what halfempty is doing, use cat instead, e.g. cat testinput | testscript.sh.

You will need to create a temporary file if your application does this, see the Examples page.

Q. I need to create short lived temporary files with very strict resource limits.

It's easy to write scripts that trap EXIT or TERM events and clean up any temporary resources, and most UNIX programmers are familiar with this shell syntax. However, if you are enforcing strict resource limits then your script might be terminated before the handlers can run.

A more correct, but arguably esoteric syntax would be like this:

#!/bin/bash
# Create and unlink a temporary file
exec 3<>${tempfile:=$(mktemp)} && rm -f ${tempfile}

# Save input to the (unlinked) temporary file
cat >&3

# Run your program
if ! yourprogram --yourargs /dev/stdin <&3; then
    exit 0 # keep this file if program fails
fi

# program succeeds, don't keep this file
exit 1

I don't use this format in documentation because fewer programmers are familiar with this syntax. However, it does mean that all resources will be cleaned up even in the event of an unexpected termination.