0% found this document useful (0 votes)
10 views3 pages

If Then+Scripts

This document provides various examples of Bash scripts that utilize if-then statements to check conditions such as variable values, file existence, and user input. It includes comparisons for numerical and string evaluations, as well as file operation checks. The document serves as a guide for writing conditional scripts in Bash.

Uploaded by

Dương Huy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views3 pages

If Then+Scripts

This document provides various examples of Bash scripts that utilize if-then statements to check conditions such as variable values, file existence, and user input. It includes comparisons for numerical and string evaluations, as well as file operation checks. The document serves as a guide for writing conditional scripts in Bash.

Uploaded by

Dương Huy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

If-then Scripts:

Check the variable

#!/bin/bash

count=100
if [ $count -eq 100 ]
then
echo Count is 100
else
echo Count is not 100
fi

Check if a file error.txt exist

#!/bin/bash

clear
if [ -e /home/iafzal/error.txt ]

then
echo "File exist"
else
echo "File does not exist"
fi

Check if a variable value is met

#!/bin/bash

a=`date | awk '{print $1}'`

if [ "$a" == Mon ]

then
echo Today is $a
else
echo Today is not Monday
fi
Check the response and then output

#!/bin/bash

clear
echo
echo "What is your name?"
echo
read a
echo

echo Hello $a sir


echo

echo "Do you like working in IT? (y/n)"


read Like
echo

if [ "$Like" == y ]
then
echo You are cool

elif [ "$Like" == n ]
then
echo You should try IT, it’s a good field
echo
fi

Other If statements

If the output is either Monday or Tuesday


if [ “$a” = Monday ] || [ “$a” = Tuesday ]

Test if the error.txt file exist and its size is greater than zero
if test -s error.txt

if [ $? -eq 0 ] If input is equal to zero (0)


if [ -e /export/home/filename ] If file is there
if [ "$a" != "" ] If variable does not match
if [ error_code != "0" ] If file not equal to zero (0)

Comparisons:
-eq equal to for numbers
== equal to for letters
-ne not equal to
!== not equal to for letters
-lt less than
-le less than or equal to
-gt greater than
-ge greater than or equal to
File Operations:
-s file exists and is not empty
-f file exists and is not a directory
-d directory exists
-x file is executable
-w file is writable
-r file is readable

You might also like