DEV Community

Cover image for Stupid Bash! Stupid me! Comparing Strings in Bash
Davide de Paolis
Davide de Paolis

Posted on

Stupid Bash! Stupid me! Comparing Strings in Bash

I usually don't write bash scripts. If use the terminal often to run AWS ClI commands, but if I need logic or something a bit more complex I'd rather go for a tiny NodeJs file.

It feels more natural to me, more readable and I can debug what is going wrong.

Sometimes though I have to touch old bash scripts used for continuous integration. Like today. Well, it was actually a YAML file used to run GilabCI Pipelines, but the job script contained a bash script, that wasn't working.

if [$CI_PIPELINE_SOURCE == "schedule"] && [[ -z "$STAGE" ]]; then
 # collapsed multi-line command
Enter fullscreen mode Exit fullscreen mode

This condition was giving an error, which was swallowed by the CI giving a successful job, but with an, of course, unexpected behavior.

27/bin/bash: line 118: [schedule: command not found
Enter fullscreen mode Exit fullscreen mode

I remembered that there was something about Single Brackets or double Brackets so I immediately changed that to

[[$CI_PIPELINE_SOURCE == "schedule"]]
Enter fullscreen mode Exit fullscreen mode


Then I remembered there was something about Wrapping Variables in Quotes therefore I changed to

[["$CI_PIPELINE_SOURCE" == "schedule"]]
Enter fullscreen mode Exit fullscreen mode


I checked the docs and Stackoverflow
After googling and trying to mix and match, Single Equal / Single Equals / Quotes in every possible allowed combination I was left staring at the script and at the StackOverflow example for a while. Until it struck me.

The space.

T h e f r e a k i n g m i s s i n g s p a c e

if [[ $CI_PIPELINE_SOURCE  == "schedule" ]] && [[ -z "$STAGE" ]]; then
Enter fullscreen mode Exit fullscreen mode


I just repropose here the Stackoverflow explanation as my own reminder

= || == ?

Bash allows == to be used for equality with [ (but this is not standard)

single or double equals?

To quote or not to quote?

Always wrap your variables with quotes, because if it is empty, your Bash script would encounter a syntax error. (Not because it would try to compare something with a null value, but because the syntax itself would be kind of broken.)

invalid equality

Hope it helps.

Top comments (2)

moopet profile image
Ben Sinclair

I heartily recommend running shellcheck to avoid this sort of thing. You can integrate it with your editor or IDE as you would any other language and it'll tell you what's wrong in excruciating detail:

shellcheck output of original source code, indicating missing spaces in the test condition

dvddpl profile image
Davide de Paolis

Awesome 🀩. Will definitely check it out. Thanks!!