Bash Variable True False if

Conditional if Checking for True or False in Bash

How to check if a Bash variable is True (false) with if statements in Bash programming language (scripting language) for Linux PCs and servers. I don't like implementing 'options' in Bash functions. So when I really need option-like functionality within a function, I use local variables.

Shou Arisaka
2 min read
Oct 30, 2025

How to check if a Bash variable is True (false) with if statements in Bash programming language (scripting language) for Linux PCs and servers.

I don’t like implementing “options” in Bash functions. Those who have implemented options know, it requires about 60 lines, well, depending on the number. So when I really need option-like functionality within a function, what do I do? Yes, I use local variables.

hoge(){

  # and more.. 

  if ( [[ "${show_hr}" == true ]] || [[ "${show_hr}" == false ]] ) && "${show_hr}" ; 
  then  
    horizonal_line
  fi 

  # and more..

}

When executing a function like the above, if you pass a local variable show_hr, it will be used within the function. In this example, if you execute like show_hr=true hoge, the commands in the if block will be executed. If you want to pass false, use show_hr= hoge or show_hr=false hoge, and if you want to pass a value, use show_hr=value hoge.

The above if block lightly validates whether the type of show_hr is boolean. Without this validation, for example, if the value of show_hr is not a boolean value but foobar, you’ll get an error like not found command: foobar. So, well, if you don’t need validation, the following writing style is okay. After thinking it through, I recommend the above writing style as the best approach.

hoge(){

  # and more.. 

  if "${show_hr}" ; 
  then  
    horizonal_line
  fi 

  # and more..

}

I can see the benefits of type declaration languages like Java. You can make arrays plural by adding the suffix s, but there isn’t really a clear rule for boolean values. show_hr_boolean is too long. Maybe it’s not bad to do it like Ruby with show_hr?. Hmm.

Addition

By the way, when it’s true, even a string becomes true, but when it’s false, a string becomes true. When getting boolean values from JSON, you might get them as strings.

In such cases, it’s good to eval it.

{
  "waked_up_once": "true"
}
if eval "$( cat "${CONFIG_JSON}" | parsejson '["waked_up_once"]' )" ; 
then 
  echo y 
fi 

Share this article

Shou Arisaka Oct 30, 2025

🔗 Copy Links