Linux Commands | Shell Script | How to Use if, for, and while Statements and Conditions

if Statement Usage and Conditions

Basic Format

if [value condition value condition...]
then
    statements
elif [value condition value condition...]
then
    statements
else
    statements
fi

Types of Conditions

Condition Description
-z True if the string length is 0
-n True if the string length is not 0
-eq True if the values are equal. Same as the = operator
-ne True if the values are different
-gt value1 > value2
-ge value1 >= value2
-lt value1 < value2
-le value1 <= value2
-a Same as the && operator, AND operation
-o Same as the `
-d True if the file is a directory
-e True if the file exists
-L True if the file is a symbolic link
-r True if the file is readable
-s True if the file size is greater than 0
-w True if the file is writable
-x True if the file is executable
file1 -nt file2 True if file1 is newer than file2
file1 -ot file2 True if file1 is older than file2
file1 -ef file2 True if file1 and file2 are the same file
#!/bin/bash

value=0 # If you write value = 0 with spaces between the variable and value, a syntax error occurs.

if [ $value = 0 ]
then
    echo "value is 0"
else
    echo "value is not 0"
fi

Execution result:

$ ./test.sh
value is 0

for Statement Usage

Basic Format

for [variable] in [loop condition]
do
    [statement]
done

Usage Example

#!/bin/bash

for i in 1 2 3
do
    echo "$i"
done

Execution result

$ ./test.sh
1
2
3

while Statement Usage and Conditions

Basic Format

while [ value1 condition value2 ]
do
   [statement]
   [statement]
done 

Usage Example

i=0

while [ $i -lt 3 ]
do
    echo $i
     i=$(($i+1))
done

Execution result:

$ ./test.sh 
0
1
2