Skip to content

test statement in bash programming

homepage-banner

Introduction

Bash is the most commonly used shell on Linux and other Unix-based operating systems. It provides a powerful scripting language for automating tasks, but it can be difficult to know where to start. In this post, we’ll focus on test statements in Bash programming. A test statement is used to evaluate an expression and return a true or false value. This allows us to make decisions in our scripts, based on conditions that are met or not met.

Testing options after if [[ ]] in bash programming:

1. Integer testing

-le    less equal
-lt    less than
-ge    greater equal
-gt    greater than
-eq    equal
-ne    not equal

2. Character testing

==
!=
>
<
-n    test if string is not null
-s    test if string is null

3. File testing

-e    test if file exists
-f    test if file is a regular file
-d    test if path is a directory
-r    test if file is readable by current user
-w    test if file is writable by current user
-x    test if file is executable by current user

For example, check if a file exists:

if [[ -e /etc/passwd ]]; then
  echo "File exist"
else
  echo "File not exist"
fi

Conclusion

Test statements are an essential part of Bash programming, allowing us to evaluate conditions and make decisions in our scripts. Understanding the different types of test statements and their syntax is crucial for creating effective and efficient scripts. We hope this post has provided you with a better understanding of test statements in Bash programming.

Leave your message