Linux Instructions and Operators
Comparison Operators in Linux (Shell Scripting)
-----------------------------------------------
These are used with `if`, `while`, or `test` commands for evaluating
conditions.
| Operator | Meaning | Example |
|----------|--------------------------|------------------------------------|
| -eq | Equal to | if [ $a -eq $b ] (True if a == b) |
| -ne | Not equal to | if [ $a -ne $b ] (True if a != b) |
| -gt | Greater than | if [ $a -gt $b ] (True if a > b) |
| -lt | Less than | if [ $a -lt $b ] (True if a < b) |
| -ge | Greater than or equal to| if [ $a -ge $b ] (True if a >= b) |
| -le | Less than or equal to | if [ $a -le $b ] (True if a <= b) |
File-Related Operators
----------------------
These are used to test file properties.
| Operator | Description | Example |
|----------|-------------------------------------------|----------------------------------|
| -e | File exists | if [ -e file.txt ] |
| -f | Regular file (not a directory) | if [ -f file.txt ] |
| -d | Directory exists | if [ -d /path/to/dir ] |
| -r | File is readable | if [ -r file.txt ] |
| -w | File is writable | if [ -w file.txt ] |
| -x | File is executable | if [ -x script.sh ] |
| -s | File is not empty | if [ -s file.txt ] |
String Comparison Operators
---------------------------
These are used for checking strings.
| Operator | Meaning | Example |
|----------|--------------------------|----------------------------------------|
|= | Strings are equal | if [ "$str1" = "$str2" ] |
| != | Strings are not equal | if [ "$str1" != "$str2" ] |
| -z | String is empty | if [ -z "$str1" ] (True if str1 empty) |
| -n | String is not empty | if [ -n "$str1" ] (True if str1 filled)|
Logical Operators
-----------------
These combine multiple conditions.
| Operator | Meaning | Example |
|----------|--------------------------|----------------------------------------|
| && | Logical AND | if [ $a -eq 5 ] && [ $b -lt 10 ] |
| || | Logical OR | if [ $a -eq 5 ] || [ $b -lt 10 ] |
|! | Logical NOT | if [ ! -f file.txt ] |
Arithmetic Operations
---------------------
Use the `expr` command or `$(( ))` for arithmetic.
| Operation | Description | Example |
|-----------|-------------------------|----------------------------------------|
|+ | Addition | sum=$((a + b)) |
|- | Subtraction | diff=$((a - b)) |
|* | Multiplication | product=$((a * b)) |
|/ | Division | quotient=$((a / b)) |
|% | Modulus (remainder) | mod=$((a % b)) |
Example Script Using These Operators
------------------------------------
#!/bin/bash
# Input two numbers
echo "Enter first number:"
read a
echo "Enter second number:"
read b
# Compare numbers
if [ $a -ge $b ]; then
echo "$a is greater than or equal to $b"
else
echo "$a is less than $b"
fi
# File operations
if [ -e sample.txt ]; then
echo "sample.txt exists"
else
echo "sample.txt does not exist"
fi
# String comparison
str1="Hello"
str2="World"
if [ "$str1" != "$str2" ]; then
echo "Strings are not equal"
else
echo "Strings are equal"
fi