You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
str1 = str2 → Returns true if both strings are the same
str1 != str2 → Returns true if both strings are different
-z str → Returns true if the string is empty
-n str → Returns true if the string is not empty
str1 > str2 → Returns true if str1 is alphabetically greater than str2
str1 < str2 → Returns true if str1 is alphabetically less than str2
Demo Program for String Comparison
Script:
#!/bin/bashread -p "Enter First String:" str1
read -p "Enter Second String:" str2
if [ $str1=$str2 ];thenecho"Both strings are equal"elif [ $str1\<$str2 ];thenecho"$str1 is less than $str2"elseecho"$str1 is greater than $str2"fi
Note:
To prevent < from being interpreted as an input redirection operator, use the backslash (\) before it.
Example Output:
Enter First String: Durga
Enter Second String: Durga
Both strings are equal
Enter First String: Apple
Enter Second String: Banana
Apple is less than Banana
Enter First String: Banana
Enter Second String: Apple
Banana is greater than Apple
Q13: Script to Check if the Login User is Root
Script:
#!/bin/bash
user=$(whoami)if [ $user!="root" ];thenecho"Current user is not root and hence exiting"exit 1
fiecho"The Five Current Running Processes Information"echo"=============================================="
ps -ef | head -5
Example Output:
Current user not root user and hence exiting
# When executed as root:
The Five Current Running Processes Information
UID PID PPID C STIME TTY TIME CMD
root 1 0 0 19:32 ? 00:00:03 /sbin/init splash
root 2 0 0 19:32 ? 00:00:00 [kthreadd]
root 3 2 0 19:32 ? 00:00:00 [rcu_gp]
root 4 2 0 19:32 ? 00:00:00 [rcu_par_gp]
Q14: Script to Test if the String is Empty or Not
Script:
#!/bin/bashread -p "Enter Any String to test:" str
if [ -z"$str" ];thenecho"Provided input string is empty"elseecho"Provided input string is not empty"echo"Its length is: $(echo -n "$str"| wc -c)"fi
Case Statement
Definition:
When multiple options are available, using nested if-else statements can make code lengthy and less readable.