From e69d9645d4525f288a8e2b8a99b2abe582ea92cc Mon Sep 17 00:00:00 2001 From: Adam Spragg Date: Mon, 4 Apr 2022 15:02:37 +0100 Subject: 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. --- adu-download | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'adu-download') 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 -- cgit v1.2.1