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 ## failed=false jobdone=true
We can now check it as follows when $failed is number such as 0 or 1:
if [ $failed -eq 1 ] then echo "Job failed" else echo "Job done" fi
OR
# true is shell command and always return 0 # false always return 1 failed=true if $failed then echo "Job failed" else echo "Job done" fi
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:
#!/bin/bash # Declare it as string failed="false" if [ "$failed" == "true" ] then echo "Job failed" else echo "Job done" fi
OR
# set it to true email_sent=true # ...do your stuff and flip email_sent to 'false' if needed ... if [ "$email_sent" = true ] then echo 'Data logged and email sent too.' else echo 'ALERT: Operation failed.' logger 'ALERT: Operation failed.' fi
Alternate syntax is as follows to define boolean variables under bash:
# Let us Declare Two Boolean Variables # Set this one to true jobstatus=true # Check it if [ "$jobstatus" = true ] ; then echo 'Okay :)' else echo 'Noop :(' fi # Double bracket format syntax to test Boolean variables in bash bool=false if [[ "$bool" = true ]] ; then echo 'Done.' else echo 'Failed.' fi
Let us test it:
Bash Boolean variable in a shell script example
Here is a sample script:
#!/bin/bash # 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/cli_app.sh" # Set failed to 'False' failed=0 D="/nfsefs/ec2mum/prodwwwroot" log="/tmp/server.log.$$.txt" # 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} do /usr/bin/rsync -az --delete backupt@${s}:/data/apps/ ${D}/${s}/ # set to 'true' when rsync failed and continue loop [ $? -ne 0 ] && failed=1 done # See if rsync failed in loop if [ $failed -eq 1 ] then 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}) --- log:end -- -- Yours faithfully, $0" fi [ -f "${log}" ] && rm -f "${log}"
Bash Boolean testing
First, define a log file:
log="/tmp/rsnapshot.$$.txt"
Let us run the rsnapshot command:
/usr/bin/rsnapshot "$1" 2>&1 | $HOME/bin/error-scanner.pl > "${log}"
Get the bash command exit status in $status as follows:
status=$?
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/error-scanner.pl) 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\" $alogs See email for detailed log." else 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" fi
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.
Conclusion
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
- Share on Twitter • Facebook • 3 comments... add one ↓
Category | List of Unix and Linux commands |
---|---|
File Management | cat |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Network Utilities | dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • jobs • killall • kill • pidof • pstree • pwdx • time |
Searching | grep • whereis • which |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Much too complicated, ”
true” and “false” are standard commands therefore the following will work and be more readable
Ah, yes. Thank you for taking the time to post an uncomplicated version.
@highbury, I reckon you know your syntax is illegal, but other than that you do’ve a point.