FUNDAMENTALS A Complete Guide for Beginners
In Bash scripts, inspecting and assessing variables’ value is a fundamental skill that empowers developers to write more sophisticated and reliable scripts. Checking variable values allows us to make informed decisions, validate user input, and tailor script behavior based on different scenarios. There are several or even, thousands of user case scenarios to check the variable value in a different context, such as checking whether the variable value is defined or contains a specific value or datatype.
However, in this article, I will discuss five different cases to assist how to check the variable value in the bash script.
5 Examples to Check Variable Value Using Bash Script
When writing complex scripts or programs, it’s essential to ensure that variables hold the expected values. By checking variable values during the execution of the script, you can quickly identify any unexpected or incorrect values, making it easier to debug and fix issues.
In this article, I am going to demonstrate five different examples of checking the variable value using the bash script. So let’s start.
1. Check If a Variable is Defined in Bash Script
In Bash scripting, you can check if a variable is defined (whether it has been assigned a value). You can pass the -z
option to the if
command or conditional expression to check the variable. Here’s a sample code to accomplish the task:
#!/bin/bash
# Check if the variable is defined
if [ -z ${variable+x} ]; then
echo "The variable is not defined."
else
echo "The variable is defined."
fi
The script uses the -z
option within an if statement
, along with parameter expansion. The expression ${variable+x}
checks if the variable, variable is set, returning the value of x if it is set, and an empty string if it’s not. The -z option then checks if the result of the parameter expansion is an empty string. If the variable is not defined, the script prints “The variable is not defined.” to the console. Otherwise, if the variable is defined, it prints “The variable is defined.” to the console.
As the variable is not defined in the given Bash code, the output returns “The variable is not defined” upon executing the var_defined.sh
bash file in the command line.
2. Verify Whether a Variable Has a Value in a Bash Script
In Bash scripts, it’s often necessary to verify if a variable holds a value or is empty, especially when handling user input or working on projects that require specific data. Several approaches can be used to perform such checks in Bash.
Here, I have provided a bash script to verify whether a variable has a value in it. Check this out and don’t forget to run the script on your own machine:
#!/bin/bash
variable=
#checking if the variable contains any value
if [ x"${variable}" == "x" ]; then
echo "No value found for the variable"
else
echo "Value found for the variable"
fi
Initially, the variable is initialized with an empty value. The if statement
then checks whether the variable is empty using the condition [ x"${variable}" == "x" ]
. To handle cases where the variable is empty or not set, the variable is prefixed with x within the comparison. If the variable is indeed empty, the script will execute the code block within the if statement, printing “No value found for the variable” to the standard output. Conversely, if the variable contains a value, the script executes the code block within the else statement, printing “Value found for the variable” to the console.
As the variable does not contain any value, the script returns “No value found for the variable” in the command line.
3. Check if a Variable Contains a Number in Bash
In Bash, variables are treated as character strings and arithmetic operations can be performed on them, even when they contain numeric data. However, before conducting arithmetic operations, it is essential to ensure that the variable holds a valid number. To verify this, you need to check that the value comprises only digits ranging from 0 to 9.
Using regular expression with an equal tilde operator =~
is one of the easiest ways to check whether the variable contains a number or not. To do the same use the following script:
#!/bin/bash
read -p "Enter a number: " var
#Emplyoing the if statement with a regular expression to verify the numeric value
if [[ $var =~ ^[0-9]+$ ]]; then
echo "${var} is a number"
else
echo "${var} is not a number"
fi
Initially, the code takes the user input var variable using the read -p
command. Accompanied by the if statement, the regular expression ^[0-9]+$
verifies whether the entire string, representing the user’s input stored in the variable var, consists solely of numeric digits from 0 to 9. If so, it returns ${var}
as a number using the echo command and returns a negative response otherwise.
As the image depicts above, the script print “23 is a number” based on the user input 23. On the contrary, the script does not acknowledge 2@3 as a number by stating “2@3 is not a number”.
4. Verify Whether Variable Equals to 0 in a Bash Script
Now there might be a situation where you need to check whether the input value is zero to refrain from taking a further decision. You can check the input value by incorporating the if statement in your script.
So, check the below script to verify whether a variable equals to 0 in bash:
#!/bin/bash
# taking user variable using read -p command
read -p "Enter a number: " var
# Check if the variable equals 0
if [ "$var" -eq 0 ]; then
echo "The input variable is Zero."
else
echo "The input variable is not Zero."
fi
The if statement
checks if the value of the variable var is equal to 0 using the -eq
operator. If the condition is true, it will print “The input variable is Zero.” to the console. Otherwise, if the condition is false, it will print “The input variable is not Zero.”
Upon the first execution, the input value is 9, therefore the command line returns “The input variable is not Zero.” whereas in the second case, the command line returns “The input variable is not Zero.” provided that the user value is 0.
5. Check a Variable Contains Text String Rather Than Integer Value
Following the previous example, you can check whether your input value is a specific text string rather than an integer. You can follow the code given below to practice the concept where I take the “hello” string to the you_variable variable and later incorporate the if statement to check whether it matches the predefined string value.
Now, follow the bash script to check if a variable contains text string rather than integer value:
#!/bin/bash
# Your variable
your_variable="hello"
# Check if the variable equals "hello"
if [ "$your_variable" = "hello" ]; then
echo "The variable is equal to 'hello'."
else
echo "The variable is not equal to 'hello'."
fi
The variable your_variable contains a string value “hello”. Then the if
statement checks if the value of your_variable is equal to the string “hello” with the [ "$your_variable" = "hello" ]
expression. If the value of your_variable is “hello” the script will print “The variable is equal to ‘hello’.” to the console. Otherwise, if the value differs from “hello”, it will print “The variable is not equal to ‘hello’.”
As the image suggests, the string value “hello” matches with the [ "$your_variable" = "hello" ]
expression, thus returning “The variable is equal to ‘hello’.” in the command line.
Conclusion
In this article, I have discussed five different scenarios to check the variable value in the bash script. Of course, there are numerous examples or user-case scenarios you can create if you want. If you have any queries or suggestions related to this article, don’t forget to comment below. I am one click away to engage in a knowledge-sharing conversation with you. Thank You!
People Also Ask
How to check a variable value in bash?
To check a variable value in bash, you can use the -z
operator inside the if
conditional statement. Here is the basic syntax: if [ -z ${variable+x} ]
. It checks if the variable value is assigned or not.
Does bash have variable types?
In Bash, variables are not explicitly declared with specific types, unlike some other programming languages that have strict typing systems. However, Bash does not have variable types. All variables in Bash are treated as strings.
How to check numeric value in Bash?
You can check if a value is numeric in Bash using the [[
double brackets with the =~
operator and a regular expression. For example: [[ $value =~ ^[0-9]+$ ]]
. This expression will return true if $value contains only numeric digits, and false otherwise.
How to read a value in Bash?
To read a value from the user in Bash, you can use the read command. The syntax is like: read -p "Enter a value: " variable_name
. With this command, you will be prompted with the message “Enter a value: “, and the input will be stored in the variable named variable_name.
How to check string length 0 in Bash?
To check if a string has a length of 0 in Bash, you can use the following one-liner: [[ -z "$string" ]]
. Replace $string with the variable or string you want to check. The [[ -z “$string” ]] expression will evaluate to true if the string has a length of 0 (empty), and false otherwise.
Related Articles
- How to Declare Variable in Bash Scripts? [5 Practical Cases]
- Bash Variable Naming Conventions in Shell Script [6 Rules]
- How to Assign Variables in Bash Script? [8 Practical Cases]
- How to Use Default Value in Bash Scripts? [2 Methods]
- How to Use Set – $Variable in Bash Scripts? [2 Examples]
- How to Read Environment Variables in Bash Script? [2 Methods]
- How to Export Environment Variables with Bash? [4 Examples]
<< Go Back to Variable Declaration and Assignment | Bash Variables | Bash Scripting Tutorial