DEV Community

Super Funicular
Super Funicular

Posted on

local bytes=$(stat ...) Hid a Missing Clip From set -e: My Bash Report Printed an Empty Size and Exited 0

A small report script prints the size of each camera clip in a folder. It runs under set -e, so the expectation is simple: if stat cannot read a clip, the script stops and the scheduled job reports a failure. In the run below, the second clip had already been removed by a cleanup job before the report reached it. The script printed an empty size, carried on to the last line, and exited 0:

#!/bin/bash
set -e
clip_bytes() {
  local bytes=$(stat -c %s "$1")
  echo "$1: ${bytes} bytes"
}
clip_bytes clips/cam1_0001.mp4
clip_bytes clips/cam1_0002.mp4
echo "report done"
Enter fullscreen mode Exit fullscreen mode
$ bash report_local.sh; echo "exit: $?"
clips/cam1_0001.mp4: 48213 bytes
stat: cannot statx 'clips/cam1_0002.mp4': No such file or directory
clips/cam1_0002.mp4:  bytes
report done
exit: 0
Enter fullscreen mode Exit fullscreen mode

The stat error is right there on the terminal, and set -e is on. The script still said report done and handed the scheduler a status of 0. Run from cron with error output thrown away, all that remained would be a line with two spaces where a number should be.

The cause is the word local.

What the line actually returns

The local bytes=$(stat ...) line looks like one thing, an assignment, but Bash runs it as a call to the local builtin with one argument. The command substitution runs first and fails, then local creates the variable and assigns it the empty output. The status of the whole line is the status of local, and the Bash manual says when that is non-zero: "The return status is zero unless local is used outside a function, an invalid name is supplied, or name is a readonly variable."

A failed command substitution is not on that list. local succeeded at its own job, so the line returns 0, and set -e has nothing to react to.

Drop the word local and the same function stops the script:

#!/bin/bash
set -e
clip_bytes() {
  bytes=$(stat -c %s "$1")
  echo "$1: ${bytes} bytes"
}
clip_bytes clips/cam1_0001.mp4
clip_bytes clips/cam1_0002.mp4
echo "report done"
Enter fullscreen mode Exit fullscreen mode
$ bash report_global.sh; echo "exit: $?"
clips/cam1_0001.mp4: 48213 bytes
stat: cannot statx 'clips/cam1_0002.mp4': No such file or directory
exit: 1
Enter fullscreen mode Exit fullscreen mode

Here the line is a plain assignment with no command name. For that case the manual gives a different rule: "If one of the expansions contained a command substitution, the exit status of the command is the exit status of the last command substitution performed."

So the plain assignment carries stat's failure, and set -e exits with status 1 before report done. Removing local is not a fix, though: bytes now leaks out of the function into the rest of the script.

The same thing happens with declare, export and readonly

local is not alone. Every builtin that takes name=value arguments returns its own status, not the status of the substitution inside the value. This script runs each form once, without set -e, and prints $? straight after it:

#!/bin/bash
f() {
  local a=$(false);    echo "local a=\$(false)    -> $?"
  declare b=$(false);  echo "declare b=\$(false)  -> $?"
  export C=$(false);   echo "export C=\$(false)   -> $?"
  readonly d=$(false); echo "readonly d=\$(false) -> $?"
  e=$(false);          echo "e=\$(false)          -> $?"
  local g; g=$(false); echo "local g; g=\$(false) -> $?"
}
f
Enter fullscreen mode Exit fullscreen mode
$ bash status_check.sh; echo "exit: $?"
local a=$(false)    -> 0
declare b=$(false)  -> 0
export C=$(false)   -> 0
readonly d=$(false) -> 0
e=$(false)          -> 1
local g; g=$(false) -> 1
exit: 0
Enter fullscreen mode Exit fullscreen mode

Four forms report 0 after false failed inside them. Only the plain assignment, and the plain assignment that follows a separate local g, pass the 1 through. A line like export CLIP_DIR=$(find_clip_dir) at the top of a camera script has the same blind spot as the local line in the report.

The fix: declare first, assign on its own line

Split the declaration from the assignment. local bytes on its own line creates the variable, and the next line is a plain assignment that carries the status of stat:

#!/bin/bash
set -e
clip_bytes() {
  local bytes
  bytes=$(stat -c %s "$1")
  echo "$1: ${bytes} bytes"
}
clip_bytes clips/cam1_0001.mp4
clip_bytes clips/cam1_0002.mp4
echo "report done"
Enter fullscreen mode Exit fullscreen mode
$ bash report_split.sh; echo "exit: $?"
clips/cam1_0001.mp4: 48213 bytes
stat: cannot statx 'clips/cam1_0002.mp4': No such file or directory
exit: 1
Enter fullscreen mode Exit fullscreen mode

The report now stops at the missing clip with status 1, bytes stays local to the function, and a scheduler watching the exit status sees a failure.

Where the split still fails: calling the function from an if

The split form only helps while set -e is active, and set -e is not active everywhere. Call the same fixed function as the test of an if and the failure disappears again:

#!/bin/bash
set -e
clip_bytes() {
  local bytes
  bytes=$(stat -c %s "$1")
  echo "$1: ${bytes} bytes"
}
if clip_bytes clips/cam1_0002.mp4; then
  echo "size logged"
fi
echo "report done"
Enter fullscreen mode Exit fullscreen mode
$ bash report_if.sh; echo "exit: $?"
stat: cannot statx 'clips/cam1_0002.mp4': No such file or directory
clips/cam1_0002.mp4:  bytes
size logged
report done
exit: 0
Enter fullscreen mode Exit fullscreen mode

stat failed, the function kept going, printed the empty size, returned 0 from its last echo, and the if took the success branch. The manual covers this case on the set page: "If a compound command or shell function executes in a context where -e is being ignored, none of the commands executed within the compound command or function body will be affected by the -e setting, even if -e is set and a command returns a failure status."

The test of an if is one of those contexts, and so is the left side of && or ||. A function written to rely on set -e changes behavior depending on how it is called, and nothing in the function itself shows it.

The form that holds up in both places is an explicit return on the line that can fail:

#!/bin/bash
set -e
clip_bytes() {
  local bytes
  bytes=$(stat -c %s "$1") || return
  echo "$1: ${bytes} bytes"
}
if clip_bytes clips/cam1_0002.mp4; then
  echo "size logged"
else
  echo "no size for clips/cam1_0002.mp4"
fi
clip_bytes clips/cam1_0001.mp4
clip_bytes clips/cam1_0002.mp4
echo "report done"
Enter fullscreen mode Exit fullscreen mode
$ bash report_return.sh; echo "exit: $?"
stat: cannot statx 'clips/cam1_0002.mp4': No such file or directory
no size for clips/cam1_0002.mp4
clips/cam1_0001.mp4: 48213 bytes
stat: cannot statx 'clips/cam1_0002.mp4': No such file or directory
exit: 1
Enter fullscreen mode Exit fullscreen mode

Inside the if, || return hands stat's status back to the caller, so the else branch runs and names the clip. Outside the if, the same function returns 1, the call fails, and set -e stops the script before report done. With no number after it, return passes on the status of the last command, which here is the failed stat.

What to check in your own scripts

  • Search for the pattern. grep -nE '(local|declare|export|readonly) +\w+=\$\(' *.sh lists every line where a builtin wraps a command substitution. Each hit is a place where a failure inside $( ) returns 0.
  • Split each hit that matters. Declare on one line, assign on the next. For readonly, assign first and mark it read-only after.
  • Add || return (or || exit) where the function might run inside an if, && or ||. Without it, the split form is only as strong as set -e, and set -e is switched off in those places.
  • Check the empty case on purpose. Point the script at a clip that does not exist and read the exit status. That one run shows which of these forms the script is using.

What I did not test

  • Other Bash versions. Every run here used GNU Bash 5.1.16 with GNU coreutils stat. The quotes are from the current online Bash manual, and what I ran matched them, but I did not run another version.
  • Other shells. I ran Bash only and did not test whether other shells handle these lines the same way.
  • set -o pipefail and inherit_errexit. Neither was set in these scripts. I did not test whether either one changes any of these results.
  • The ERR trap. None of the scripts set a trap on ERR, so I did not test which of these failures would fire one.
  • Real clips and real deletions. The clip here is a file filled with zero bytes, and the missing clip did not exist. Nothing was uploaded or deleted. The scripts only print.

Sources. Quotes are from the GNU Bash Reference Manual pages Bash Builtin Commands, Simple Command Expansion and The Set Builtin. Outputs are pasted unedited from the scripts above.

If you want an old Android phone recording in the background so there is a folder of clips for a script like this to report on, the app I make is Background Camera RemoteStream on Google Play. Nothing above depends on it.

A command substitution inside local, declare, export or readonly returns the builtin's status, not its own, so give the variable its own declaration, put the substitution in a plain assignment, and add || return wherever the function might be called from an if.

Top comments (0)