diff options
author | Adam Spragg <adam@spra.gg> | 2022-04-04 15:02:37 +0100 |
---|---|---|
committer | Adam Spragg <adam@spra.gg> | 2022-04-04 15:02:37 +0100 |
commit | e69d9645d4525f288a8e2b8a99b2abe582ea92cc (patch) | |
tree | 32d2411ceacde1d6d426c46a682c97ce9ed62b7a | |
parent | 1e1e75f0d5c6e6bfbf67b36266aa97edc7fb8bf1 (diff) |
Fix upgrade count when there are no upgrades
There's a difference between
cmd | wc -l
and
x="$(cmd)"; echo "$x" | wc -l
in that the assignment in the latter removes a trailing newline **if one
exists**, but the "echo" always adds one. This means that if `cmd`
produces no output, the former has 0 lines, and the latter has 1 (empty)
line.
I've not found an easy way to fix this in a way that `wc` can tell the
difference between an empty line and a non-empty one, so I had to find a
separate way to count non-empty lines.
I did try `echo "$x" | grep . | wc -l`, but `shellcheck` complains with
[SC2126](https://github.com/koalaman/shellcheck/wiki/SC2126). The
suggested alternative, `echo "$x" | grep -c .`, causes a failure on
empty inputs (i.e. when there are no upgrades) because `grep` exits with
a failure status if no lines are selected.
My options were then to go with `grep | wc` and silence the warning, or
do `grep -c | cat` to mask the `grep` failure (again). Given that they
both have the same number of commands in the pipe, but `cat` is probably
*slightly* cheaper than `wc`, and the `cat` version doesn't require
adding a `shellcheck`-silencing comment, let's go with that.
-rwxr-xr-x | adu-download | 2 |
1 files changed, 1 insertions, 1 deletions
diff --git a/adu-download b/adu-download index 9fcf505..dff7501 100755 --- a/adu-download +++ b/adu-download @@ -30,7 +30,7 @@ UPDATE_TARGET="${SBINDIR}/adu-upgrade" apt-get -qq update upgradeable=$(apt -qq list --upgradeable 2>/dev/null) -upgrades=$(echo "$upgradeable" | wc -l) +upgrades=$(echo "$upgradeable" | grep -c . | cat) if [ "$upgrades" -eq 0 ]; then exit 0 fi |