Operators In Bash Scripts

Table of contents

Bash scripting provides a variety of operators that can be used to check and perform operations on files, strings, and numbers. These operators are essential for implementing conditional logic, handling user input, validating data, and managing system resources efficiently in shell scripts.
File Operators
File operators return values in true(0) and false(1)
-d → this operator checks weather the director is present is or not.
Usually if answer is true then this will return nothing. If we want to check what was value returned then we use “$?” operator. This operator gives us Exit Code(discussed in separate blog) which is either 0 or 1.
In the below image : directory named functions is already created and we are using -d operator to check.
[reminder - use space before using -d and at the end otherwise terminal may not recognize the operator]
-e → The operator checks if file exists.
-f → The operator checks if file is regular file and if yes returns true
-r → Returns true if file is readable by you.
-s → Return true if file exists and is not empty.
-w → Return true if file is writable by you.
-x → If file is executable by you.
In the above image when -x is used 1 returns that is because new file (text1.txt) is only created. To make these file executable we use “chmod +x filename.txt”
String Operators
Return value for string operator are similar as file operator. The return values are true(0) and false(1).
-z → Checks if the string is empty and if yes return true.
-n → Checks if the string is not empty and if yes return true.
string1 = string2 → true if the string are equal.
string1 != string2 → true if the string are not equal.
\> → True if string is lexically greater than other.
< → True if string is lexically smaller than other.
(Lexically means → checking string character by character and based on ASCII value)
Arithmetic Operator
Return value for arithmetic operator are similar as file operator. The return values are true(0) and false(1).
(num→ here means numbers)
num1 -eq num2 → Returns true if num1 is equal to num2.
num1 -ne num2→ Returns true if num1 is not equal to num2.
num1 -lt num2→ Returns true if num1 is less than num2.
num1 -le num2→ Returns true if num1 is less than and equal to num2.
num1 -gt num2→ Returns true if num1 is greater than num2.
num1 -ge num2→ Returns true if num1 is greater than and equal to num2.
Repository link
You can find all the scripts mentioned in this article in the repository below:
https://github.com/ishaj72/Bash-Scripting
Stay tuned for the next article, where we will explore if-else conditions and exit codes in Bash scripting.
Happy reading!!
Subscribe to my newsletter
Read articles from Isha Jain directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Isha Jain
Isha Jain
An enthusiast about continuously broadening my horizons in the dynamic world of technology.