How to declare Boolean variables in bash and use them in a shell script

I need to define a bash variable called failed and set the value to False. When my script is called from a cron job, specific tasks might fail, and then I need to flip failed to True. Based upon $failed, I need to send an email alert that my cron job has failed. So how can I declare and use Boolean variables in a shell script running on a Linux server?

There are no Booleans in Bash. However, we can define the shell variable having value as 0 (“False“) or 1 (“True“) as per our needs. However, Bash also supports Boolean expression conditions. Let us see how to combine these two concepts to declare Boolean variables in Bash and use them in your shell script running on Linux, macOS, FreeBSD, or Unix-like system.

Declaring Boolean variables in bash

The syntax is as follows to define something as follows

failed=0 # False
jobdone=1 # True
## more readable syntax ##

We can now check it as follows when $failed is number such as 0 or 1:

if [ $failed -eq 1 ]
    echo "Job failed"
    echo "Job done"


# true is shell command and always return 0 
# false always return 1 
if $failed
    echo "Job failed"
   echo "Job done"

That is it all.

How to declare and use Boolean variables such as “true” and “false” in a shell script

Of course, we can define them as a string and make our code more readable:

# Declare it as string 
if [ "$failed" == "true" ]
    echo "Job failed"
    echo "Job done"


# set it to true
# your stuff and flip email_sent to 'false' if needed ...
if [ "$email_sent" = true ] 
    echo 'Data logged and email sent too.'
    echo 'ALERT: Operation failed.'
    logger 'ALERT: Operation failed.'

Alternate syntax is as follows to define boolean variables under bash:

# Let us Declare Two Boolean Variables
# Set this one to true
# Check it 
if [ "$jobstatus" = true ] ; then
	echo 'Okay :)'
	echo 'Noop :('
# Double bracket format syntax to test Boolean variables in bash
if [[ "$bool" = true ]] ; then
	echo 'Done.'
	echo 'Failed.'

Let us test it:

Bash Boolean variable in a shell script example

Here is a sample script:

# Author : Vivek Gite
# Purpose: Backup stuff from /data/apps
# Tested on : AWS EC2 with EFS and Ubuntu 20.04 Pro servers
# ---------------------------------------------------------
source "/apps/.keychain/$HOSTNAME-sh"
source "/apps/scripts/"
# Set failed to 'False' 
# Log everything to our file
exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>"${log}" 2>&1
# Backup all web servers
for s in www-0{1..8}
        /usr/bin/rsync -az --delete backupt@${s}:/data/apps/ ${D}/${s}/
        # set to 'true' when rsync failed and continue loop  
        [ $? -ne 0 ] && failed=1
# See if rsync failed in loop 
if [ $failed -eq 1 ]
        echo "$0 script error: rsync backup failed. See attached log file." | mail -A ${log} -s "$HOSTNAME - LXD backup failed" -r sysuser@my-corp-tld alert@somewhere-tld
        push_to_mobile "$0" "Dear sysadmin,
        Backup failed at $HOSTNAME at $(date). 
        ---- log:start ---
        --- log:end --
        Yours faithfully,
[ -f "${log}" ] && rm -f "${log}"

Bash Boolean testing

First, define a log file:


Let us run the rsnapshot command:

/usr/bin/rsnapshot "$1" 2>&1 | $HOME/bin/ > "${log}"

Get the bash command exit status in $status as follows:


Next search for ERROR in our $log file:

alogs="$(egrep -w '^ERROR:|ERROR' $log)"

If $status is not zero (failed command) or $alogs is NOT empty (errors reported by $HOME/bin/ then alert sysadmin or developers via email/text message:

if [ $status -ne 0 ] ||  [ "$alogs" != "" ]; then
        sub="Backup job failed at $HOSTNAME"
        mail -A "$log" -s "$sub" -r sys@somewhere-tld sysadmin@gmail-tld <<< "$0 script ended with errors when we ran /usr/bin/rsnapshot \"$1\" $alogs"
        push_to_mobile "$0" "$sub
        $0 script ended with errors when we ran /usr/bin/rsnapshot \"$1\"
        See email for detailed log."
        sub="Backup successful at $HOSTNAME"
        #push_to_mobile "$0" "$sub. See email for detailed backup log." >/dev/null
        #mail -A "$log" -s "$sub" -r sys@somewhere-tld sysadmin@gmail-tld <<< "$0 /usr/bin/rsnapshot ran successfully\"$1\" $alogs"

Finally, remove the $log file:

[ -f "$log" ] && rm -f "$log"

See “How to push/send message to iOS and Android from Linux CLI” for more info.


We explained how to declare and use Boolean variables in a shell script/bash on Linux or Unix-like systems using various methods. See the following man pages using the man command (or read it online):
$ man bash
$ help test
$ help if

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 3 comments so far... add one

CategoryList of Unix and Linux commands
Disk space analyzersdf duf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Modern utilitiesbat exa
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg glances gtop jobs killall kill pidof pstree pwdx time vtop
Searchingag grep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
3 comments… add one
  • highbury Dec 25, 2020 @ 10:52

    Much too complicated, ”
    true” and “false” are standard commands therefore the following will work and be more readable

    if $failed
     then : "failed is true"
     else : "failed is false"
    • 🐧 Vivek Gite Dec 25, 2020 @ 12:53

      Ah, yes. Thank you for taking the time to post an uncomplicated version.

    • Jouni "rautamiekka" Järvinen Jan 3, 2021 @ 21:51

      @highbury, I reckon you know your syntax is illegal, but other than that you do’ve a point.

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum