You could do something like:
if cmd | { first_byte=$(dd bs=1 count=1 2> /dev/null | od -An -vto1) [ -n "$first_byte" ] && printf "\\$(( $first_byte ))" && cat } then echo non-empty fi If you can install extra software, then you can use moreutils' ifne:
if cmd | ifne -n false; then echo non-empty fi About your dealbreakers:
output=$(cmd) sets a shell variable and I don't know of any sh implementation that has a limit on the length of its variables. It only becomes an environment variable if you export it and execute a command, and then you may be hit the system's limit on the size of the argv[] + envp[] passed to execve()
That same limit would apply for argv[] in the printf %s "$output" in those sh implementations where printf is not builtin (such as ksh88 or some pdksh-derived shells).
$(...) strips trailing newlines and in most implementations either chokes on or removes NULs. yash would choke on outputs that cannot be decoded as text in the locale.
As seen at How create a temporary file in shell script?, there is a POSIX CLI API to mkstemp() in m4:
tmpfile=$( echo 'mkstemp(template)' | m4 -D template="${TMPDIR:-/tmp}/baseXXXXXX" ) || exit Though systems without m4 are not rare (even though it's a non-optional POSIX utility).