FUNDAMENTALS A Complete Guide for Beginners
In Bash scripting, it’s very common to perform conditional tests and comparisons on variables, strings, files or directories. In this effort, Bash provides plenty of options to use with the ‘if’ statement. These options along with the ‘if’ statement help to control the flow of scripts by employing conditional executions based on numeric values, string values, file or directory properties, permissions etc.
In this article, I will discuss the 10 most useful options of the ‘if’ statement in Bash.
What is “if” Statement in Bash?
The ‘if’ statement in Bash is a basic control structure utilized for certain command executions according to specific conditions and performing different comparisons and checks. This conditional statement is generally used to evaluate if a condition is true or false. When a condition evaluates to true, it returns an exit status of zero (0) i.e. it means successful execution. On the contrary, when a condition evaluates to false, it returns a non-zero exit status i.e. it executes nothing.
10 Most Useful Options of the “if” Statement in Bash
The ‘if’ statement in Bash is employed for conditional execution. Several options with an ‘if’ statement determine the status of a file or directory. Some of the most frequently used options in Bash scripts are -s, -n, -f, -e, -d, -v, -z, -r, -w and -x. Here’s an overview of the most useful options for the ‘if’ statement in Bash:
1. Bash “If -s”
The “-s” option within an ‘if’ conditional statement in Bash is used to check if a file exists and has a size greater than zero i.e. whether it contains any content or not. If the condition is satisfied, the “-s” option returns a a zero exit status meaning that the file is not empty. Otherwise, the “-s” option returns nothing.
Now, consider a file having some contents inside:
# shop.txt
1. Laptop
2. Mouse
3. Keyboard
To check if a file exists and has a non-zero size (not empty) in Bash, check out the script below:
#!/bin/bash
file_name="shop.txt"
if [ -s "$file_name" ]; then
echo "The file '$file_name' is not empty."
fi
In the script, the if [ -s "$file_name" ];
syntax checks if the file exists and contains any text or data. If the file exists and is not empty, the script returns a true expression with an output message.
From the image, you can see that the file shop.txt in my system contains some content which means it is not empty.
2. Bash “If -n”
The “-n” option in Bash is a string comparison operator that is used to check if a string variable is not empty i.e. if it contains a value with more than zero length. The syntax [ -n String ]
with an ‘if’ statement is used to accomplish the conditional check. When the string contains one or more characters, it evaluates to true; otherwise, It returns nothing if the string is empty.
Here’s a Bash script to evaluate whether a string is not empty:
#!/bin/bash
my_string="Linuxsimply"
if [ -n "$my_string" ]; then
echo "The string is not empty."
fi
In the script, the if [ -n "$my_string" ];
syntax checks if the string has a length greater than zero. If the string has a non-zero length and is not empty, the script returns a true expression.
As you can see from the image, the string variable contains the value ‘linuxsimply’ which is of non-zero length.
3. Bash “If -f”
The “-f” option in Bash checks if a file exists and if it is a regular file. A regular file in Bash is a specific type of file that includes text, data or pieces of programs. The syntax for using the “-f” option is [ -f FILE_NAME ]
.
To check if a file exists and is a regular file, use the “-f” test operator within an ‘if’ statement like the following script:
#!/bin/bash
if [ -f "linux.txt" ]; then
echo "The file 'linux.txt' exists."
fi
Here, the ‘if’ statement checks if the file exists and is a regular file. If the condition evaluates to true, the script executes ‘The file exists.’.
In the image, you can see that in my system, the file linux.txt exists and it is a regular file.
4. Bash “If -e”
The “-e” option within the ‘if’ conditional statement in Bash is used to check the existence of a file or directory. If the specified files or directories exist in the filesystem, it evaluates to true; otherwise, it returns nothing.
Go through the following script to check if a specific file path exists in Bash:
#!/bin/bash
file_path="/home/nadiba/Documents/notice.txt" #Providing information in /path/to/file_name
if [ -e "$file_path" ]; then
echo "'notice.txt' exists"
fi
In the script, if [ -e "$file_path" ];
verifies whether the specific file exists in the specific path. If it exists, the script executes a true expression.
In the above image, you can see that the file notice.txt exists inside ‘/home/nadiba/Documents’ in my system.
5. Bash “If -d”
The “-d” option in Bash is used to check if a specified path exists and is a directory. Directories are folders that can contain multiple files or subdirectories. Use the syntax [ -d FILE_NAME ]
with an ‘if’ statement to perform conditional tests on directories in Bash.
To verify the existence of a directory in Bash, you can follow the script below:
#!/bin/bash
directory_path="/home/nadiba/Desktop/Bash global variable" #Providing information in /path/to/directory
if [ -d "$directory_path" ]; then
echo "The directory exists."
fi
Here, the ‘if’ statement checks if the defined path corresponds to an existing directory. If the condition is satisfied, the script returns an exit status of zero implying success.
This image represents that the mentioned directory Bash global variable exists inside ‘/home/nadiba/Desktop’ in my system.
6. Bash “If -v”
The “-v” option is not directly related to conditional statements in Bash. It is generally used with the set
command to enable the verbose mode displaying each command and its arguments before the execution. However, this option can be used indirectly within an ‘if’ statement to check if a variable is set or not in Bash by utilizing the syntax if [ -v FILE_NAME ];
. Here’s a Bash script to evaluate whether a variable is set or assigned:
#!/bin/bash
#Declaring two variables
variable1="abc"
variable2=""
#Checking if variables are set
#For variable1
if [ -v variable1 ]; then
echo "'Variable1' is set with a non-empty string."
fi
#For variable2
if [ -v variable2 ]; then
echo "'Variable2' is set with an empty value."
fi
Here, if [ -v variable1 ];
and if [ -v variable2 ];
check if variable1 and variable2 are assigned or set with some values or not. If the conditions are satisfied, the script echoes the respective outputs employing the echo command.
The above image depicts that variable1 and variable2 both variables are set as they are assigned with values like ‘abc’ and an empty string respectively.
7. Bash “If -z”
The “-z” option, a string comparison operator with an ‘if’ statement in Bash is used to check if a string variable is empty i.e. if it contains a value with zero length. In this effort, use the syntax [ -z String ]
with the ‘if’ conditional statement to check null strings in Bash. If the string is empty, it returns true expression. However, if the string contains any value with non-zero length, it executes nothing.
Check the following script to verify if a string is empty in Bash:
#!/bin/bash
my_string=""
if [ -z "$my_string" ]; then
echo "The string is empty."
fi
In the script, if [ -z "$my_string" ];
evaluates whether ‘my_string’ string variable is empty. If it is empty, the script executes a true expression with an output message.
The above image states that the given string my_string contains a zero length value which is an empty string.
8. Bash “If -r”
In Bash scripting, the “-r” option is used within conditional statements to check if a file or directory has read permissions for the effective user ID (EUID) running the script. It’s commonly used with the test command (or [ ] construct) to assess file permissions.
The “-r” flag evaluates to true if the specified file or directory is readable by the user executing the script; otherwise, it returns nothing. Go through the script below to check if a file has read permission in Bash:
#!/bin/bash
file_name="color.txt"
#Checking if the file has read access
if [ -r "$file_name" ]; then
echo "The file '$file_name' is readable."
fi
In this script, if [ -r "$file_name" ];
verifies whether the file has read permission. If it has read permission, the script executes a true expression.
In the image, you can see that the file color.txt in my system has read permission.
9. Bash “If -w”
The “-w” option within an ‘if’ statement in Bash is used to check if a file or directory has write permissions for the EUID. The basic syntax to accomplish the task is if [ -w FILE_NAME ];
.
Check out the following Bash script to check if a file is writable:
#!/bin/bash
file_path="/home/nadiba/Pictures/animal.txt" #Providing information in /path/to/file_name
#Checking if the file has write access
if [ -w "$file_path" ]; then
echo "The file 'animal.txt' is writable."
fi
Here, if [ -w "$file_path" ];
evaluates if the file has writing access. If it is writable, the script executes a true expression with an output message.
In the above snapshot, you can see that the file animal.txt inside ‘/home/nadiba/Pictures’ in my system has write permission.
10. Bash “If -x”
The “-x” option in Bash is used to check whether a file exists and has execute permissions for the user (the owner) running the script (without considering other users or group). This option in conjugation with the ‘if’ statement can be used to perform the conditional checks by utilizing the syntax if [ -x FILE_NAME ];
.
Review the script below to check if a file exists and is executable:
#!/bin/bash
file_name="argument.sh"
#Checking if the file has execute permission
if [ -x "$file_name" ]; then
echo "The file '$file_name' is executable."
fi
Here, if [ -x "$file_name" ];
verifies whether the file has execution permission. If the file is executable, the script executes a true expression.
In the above image, you can see that the file argument.sh in my system has execute permission.
Conclusion
All the options mentioned in the article provide flexible conditional checks within Bash scripts. By understanding the proper use of these options, you can enhance your scripts’ functionality and effectiveness.
People Also Ask
Can I combine multiple options within a single ‘if’ statement in Bash?
Yes, you can combine multiple options within a single ‘if’ statement in Bash by using logical operators such as && and ||. For example:
#!/bin/bash
file_name="example.txt"
if [ -e "$file_name" ] && [ -f "$file_name" ]; then
echo "The file '$file_name' exists and is a regular file."
fi
Can I toggle an option within an “if” statement using a flag in Bash?
Yes, you can toggle an option within an if statement using a flag or a variable in Bash by changing its state based on certain conditions. For example:
#!/bin/bash
#Setting a flag
option=false
#Toggling the flag
if [ condition ]; then
option=true #Enabling the option if the condition is satisfied
else
option=false #Disabling the option if the condition is not satisfied
fi
#Perform actions based on the toggled state of the flag
if [ "$option" = true ]; then
echo "Now, option is enabled."
else
echo "Now, option is disabled."
fi
Which Bash options can help in the process of debugging?
Bash provides several options to help in the debugging process such as ‘set -e’, ‘set -u’, ‘set -x’ etc. Using these options you can easily trace different commands, understand scripts’ behavior and identify functional errors.
What if I want to perform actions based on whether a symbolic link exists or not?
If you want to perform actions based on whether a symbolic link exists or not, you can combine the ‘-e’ option and the ‘-L’ option within an ‘if’ statement. For example:
#!/bin/bash
if [[ -e "/path/to/file_name" && -L "/path/to/file_name" ]]; then
echo "The file exists and is a symbolic link."
fi
Related Articles
- How to Check a Boolean If True or False in Bash [Easy Guide]
- Bash Test Operations in ‘If’ Statement
- Check If a Variable is Empty/Null or Not in Bash [5 Methods]
- Check If a Variable is Set or Not in Bash [4 Methods]
- Check If Environment Variable Exists in Bash [6 Methods]
- Bash Modulo Operations in “If” Statement [4 Examples]
- How to Use “OR”, “AND”, “NOT” in Bash If Statement [7 Examples]
- Evaluate Multiple Conditions in Bash “If” Statement [2 Ways]
- Using Double Square Brackets “[[ ]]” in If Statement in Bash
- 6 Ways to Check If a File Exists or Not in Bash
- How to Check If a File is Empty in Bash [6 Methods]
- 7 Ways to Check If Directory Exists or Not in Bash
- Negate an “If” Condition in Bash [4 Examples]
- Check If Bash Command Fail or Succeed [Exit If Fail]
- How to Write If Statement in One Line? [2 Easy Ways]
- Different Loops with If Statements in Bash [5 Examples]
- How to Use Flags in Bash If Condition? [With Example]
- Learn to Compare Dates in Bash [4 Examples]
<< Go Back to If Statement in Bash | Bash Conditional Statements | Bash Scripting Tutorial