One empty variable, one error, one wrong answer, exit 0

●1 ●26 ●90
calendar_today • schedule1 min read

I wrote four lines to capture a bash error for a guide. One empty variable, tested twice:

$ cat queue-check.sh
#!/bin/bash
count=""
if [ $count -eq 0 ]; then echo "queue empty"; fi
if [[ $count -eq 0 ]]; then echo "queue empty ([[ ]])"; fi

$ bash queue-check.sh
queue-check.sh: line 3: [: -eq: unary operator expected
queue empty ([[ ]])
exit=0

The message blames -eq. The bug is the unquoted $count before it: word splitting removed the empty value, so [ received -eq 0 and failed with status 2, which an if treats as "not true". The [[ ]] line does no splitting, read the empty string as 0 in an arithmetic test, and printed a confident wrong answer. Then the script exited 0.

Strict mode does not help here. count="" is set, so set -u stays quiet, and set -e ignores failures inside an if condition. What stopped it was validating the value first: [[ $count =~ ^[0-9]+$ ]] || exit 1.

Most bash errors work this way. The message names the check that failed, not the cause: a syntax error reported on line 4 for a missing semicolon on line 2, Permission denied after chmod +x on a noexec mount. Nine of them, each reproduced with the check that names the cause, are in Bash Error Messages, Decoded.

🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

More Posts

My 30-day log cleanup kept a file that was 30 and a half days old

BashSnippets - Oct 8

The log was deleted. Its 48M was still allocated.

BashSnippets - Oct 28

I killed the process I started. The port stayed taken.

BashSnippets - Nov 5

A Textile Mill's Dyehouse Ramp Curve: Get One Step Wrong and the Sheet Belongs to the Master

aiomniu - Oct 18

bash ran a path that no longer existed, and exited 127

BashSnippets - Oct 21
chevron_left
4k Points • 117 Badges
North America • bashsnippets.xyz
77Posts
35Comments
10Connections
Linux user who got tired of Googling the same bash commands every time I sat down at a terminal. Sta... Show more

Related Jobs

View all jobs →

Commenters (This Week)

9 comments
4 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!