How to Return Boolean From Bash Function [6 Methods]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

To return a boolean from the function in Bash, use the following methods:

  1. Using “return” Statement: my_function() { if return 0; else return 1; fi;}
  2. Using “true” or “false” Commands: my_function() { if true; else false; fi;}
  3. Using “echo” Command: my_function() { if echo “true”; else echo “false”; fi;}
  4. Using Case Statement: my_function() {case expression in; true) return 0 ;; *) return 1 ;; esac;}
  5. Using Logical Operators: my_function() { command && return 0 || return 1; }
  6. Using an Array: my_function() { array= (“true” “false”); command && echo ${array[0]} || echo ${array[1]; }

While working with functions in bash, it returns the boolean value to show whether the command succeeded or failed. Although bash does not support the built-in Boolean data type, boolean values are represented using the exit codes 0 (True) and 1 (False). The exit code 0 indicates success and the exit code 1 indicates failure. Besides, there are two special commands “true” and “false” to signify the command’s success and failure respectively. In this article, I will show you the 6 methods of returning a boolean from the bash function. Let’s start.

1. Using “return” Statement

Explicit use of the return statement adds more clarity to the script. When a function returns 0, it indicates true. On the other hand, a value of 1 means the function returns false. Here’s how:

#!/bin/bash

check_even() {
 if (( $1 % 2 == 0 )); then
  echo "Even number,return $?"
  return 0  # True
 else
  echo "Odd number,return $?"
  return 1  # False
 fi
}

number=10
check_even $number
EXPLANATION

Here, a function is defined named check_even. (( $1 % 2 == 0 )) within the function uses an arithmetic expansion to determine if the number is even. The script returns 0 if true (number is even) and 1 if false (number is odd). After calling the function, the script checks the exit code using $?. If the exit code is 0, it means the number is even, and it echoes “Even number, return 0”. When the exit code is 1, it means the number is odd, and it echoes “Odd number, return 1”

returns boolean from function using return statement

The script returns 0 as the number 10 is even.

2. Using “true” or “false” Commands

To return a boolean value like “true” or “false” from the bash function, directly integrate the true and false commands with the function. Here is the full bash script to do this:

#!/bin/bash

check_positive() {
 if (( $1 > 0 )); then
  true  # positive
 else
  false  # non-positive
 fi
}

number=7
if check_positive $number; then
 echo "Positive number"
else
 echo "Non-positive number"
fi
EXPLANATION

This script defines a function named check_positive that takes an input argument using $1. After that, it checks if the argument is greater than 0 using the (( $1 > 0 )) arithmetic expression. If true, it executes the true command, indicating a positive number. If not, it executes the false command, indicating a non-positive number.

number=7 sets the variable number to the value 7. check_positive $number calls the function with the value of the number variable as an argument. If the function returns true (exit code 0), it echoes “Positive number”. It echoes “Non-positive number” when the function returns false (exit code 1).

returns boolean from function using true-false commands

As you can see, it shows “Positive number” because the number 7 is positive and the function returns true.

3. Using “echo” Command

The echo command command offers a more concise way to return the boolean value from the function. The function echoes the “true” string if the specified condition is true, it will return false otherwise. Now, check the bash script to see how the function returns a boolean value with the echo command:

#!/bin/bash

check_true() {
 if [ 1 -eq 1 ]; then
  echo "true"
 else
  echo "false"
 fi
}
check_true
EXPLANATION

In this script, the check_true function uses an echo command to return a boolean true or false. Inside the function, the if statement checks if 1 is equal to 1. As the condition is true the function returns “true”. If a false condition is written inside the if statement, it will trigger to return the string “false”.

returns boolean from function using echo command

Since the specified condition is true, the function echoes “true”.

4. Using Case Statement

A case statement can be incorporated with the function in bash to return boolean values. When the expression of the case statement matches with the specified pattern, the function returns true. Here’s the entire bash script to get a clear insight:

#!/bin/bash

get_true() {
 case "$1" in
  true) return 0 ;;  # true
  *) return 1 ;;    # false
 esac
}

if get_true "true"; then
 echo "It is true"
else
 echo "It is false"
fi
EXPLANATION

Here, a get_true function is defined that takes an argument and uses a case statement to check its value. If the value of the argument is equal to “true”, the function returns 0. Otherwise, it returns 1.

get_true "true" calls the function with the argument ‘true”. The script echoes “It is true” when the function returns true. On the other hand, it will echo “It is false”.

returns boolean from function using case statement

The script echoes  “It is true” because the function returns “true”.

5. Using Logical Operators

Bash offers a bunch of logical operators such as AND or OR. Combining these operators with a function can return boolean values like “true” or “false” depending on the condition. Here’s how:

#!/bin/bash

check_odd() {
 local result
 (( $1 % 2 != 0 )) && return 0 || return 1
}

check_odd 5
if [ $? -eq 0 ]; then
 echo "Odd number"
else
 echo "Even number"
fi
EXPLANATION

Inside the check_odd function, (( $1 % 2 != 0 )) && return 0 || return 1 uses arithmetic expansion and logical operators (&& and ||) to check whether the given argument is an odd number. If so, the function returns 0 (indicating true), else it returns 1 (indicating false).

check_odd 5 calls the function with argument 5. After that, $? -eq 0 condition within the if statement checks the exit status of the last executed command. When the function returns 0 exit status, the script prints “Odd number”. Conversely, it prints “Even number”.

returns boolean from function using logical operators

You can notice that the bash script prints “Odd number” as the function returns 0 (true).

6. Using an Array

An array can be used to return a boolean true or false result from a function in bash. For this purpose, the array should contain two elements, true and false. Consider the test of the existence of a file with the -e option. If the file exists, ${array[0]} will return the array element “true”. If not, ${array[1]} will return “false”. Now, copy the script to accomplish this task:

#!/bin/bash

function file_exist() {
 local result=("true" "false")

 # Check if the file "file.txt" exists
 [ -e "file.txt" ] && echo ${result[0]} || echo ${result[1]}
}

# Call the function
file_exist
EXPLANATION

This script checks if the file “file.txt” exists using the file_exist function. A local array variable named “result” is declared. This array contains two elements: “true” and “false,” representing the boolean values that will be echoed based on the file existence condition. After running it, if “file.txt” exists in the same directory, it will output “true”; otherwise, it will output “false.”

returns boolean from function using arrays

Since the “file.txt” does not exist, the function returns “false”.

Practice Tasks on Returning Boolean From Bash Function

Practicing writing functions that return boolean values is a great way to improve Bash scripting skills. Here are some tasks for you:

  1. Define a function that returns true if a string is not empty. If it is empty, it should return false.
  2. Develop a function that checks whether two strings are equal. If it is, it should return true, otherwise false.
  3. Write a Bash script that defines a function to evaluate if a particular directory exists. The function should return true or false based on the existence of the directory.
  4. Generate a function that uses a case statement to check if a string holds a valid IP address. The function should return true if it does, otherwise, it should return false.

Conclusion

To wrap up, I have provided 6 methods to return a boolean value from a function in bash. Pick the method that is best for you. Lastly, don’t forget to perform the practice work. Good Luck!

People Also Ask

How can I return a boolean value from a function in Bash?

To return a boolean value such as true or false, you can use the return statement. The return statement with argument 0 means true and argument 1 indicates false.

What is boolean value in bash?

The boolean value in bash is used to determine the success or failure of a command. It contains two types of data: 0 and 1; where 0 denotes true or success and 1 denotes false or failure.

How to use boolean value in Bash?

Though Bash does not support boolean values directly, you can use exit code to represent the boolean values. Like, exit status 0 means true and 1 means false.

Is it possible to pass boolean values in Bash?

Yes, it is possible to pass boolean values in bash. One of the most common techniques is to use strings (true or false) or numbers (0 for True, 1 for False).

Related Articles


<< Go Back to Return Values From Bash Function | Bash Functions | Bash Scripting Tutorial

Rate this post
Mitu Akter Mou

Hello, This is Mitu Akter Mou, currently working as a Linux Content Developer Executive at SOFTEKO for the Linuxsimply project. I hold a bachelor's degree in Biomedical Engineering from Khulna University of Engineering & Technology (KUET). Experiencing new stuff and gathering insights from them seems very happening to me. My goal here is to simplify the life of Linux users by making creative articles, blogs, and video content for all of them. Read Full Bio

Leave a Comment