Linux and Shell Programming

0 of 30 lessons complete (0%)

Module 6 Introduction to Shell

Example

#!/bin/bash

# This is a shebang line that tells the system to use bash to interpret this script.

# Assigning values to variables
num1=10
num2=20

# Comparing if num1 is less than num2
if [ $num1 -lt $num2 ]; then
    echo "$num1 is less than $num2"
fi

# Comparing if num1 is equal to num2
if [ $num1 -eq $num2 ]; then
    echo "$num1 is equal to $num2"
fi

# Comparing if num1 is not equal to num2
if [ $num1 -ne $num2 ]; then
    echo "$num1 is not equal to $num2"
fi

# Comparing if num1 is greater than num2
if [ $num1 -gt $num2 ]; then
    echo "$num1 is greater than $num2"
fi

# Comparing if num1 is greater than or equal to num2
if [ $num1 -ge $num2 ]; then
    echo "$num1 is greater than or equal to $num2"
fi

# Comparing if num1 is less than or equal to num2
if [ $num1 -le $num2 ]; then
    echo "$num1 is less than or equal to $num2"
fi

Explanation:

  1. #!/bin/bash: This is known as a shebang line. It indicates that the script should be interpreted and executed using the Bash shell.
  2. num1=10 and num2=20: These lines assign values to two variables, num1 and num2.
  3. if [ $num1 -lt $num2 ]; then: This is a conditional statement. It checks if num1 is less than num2. If this condition is true, the code within the if block will execute.
  4. echo "$num1 is less than $num2": This line prints a message to the console if the condition in the previous line is true.
  5. The script goes on to perform other comparisons (-eq, -ne, -gt, -ge, -le) in a similar fashion.
  6. Each conditional block is terminated with fi, which is if spelled backward.

To run this script, save it in a file (e.g., number_comparison.sh) and make it executable using the command chmod +x number_comparison.sh. Then, you can execute it with ./number_comparison.sh.

When you run this script, you will see output based on the comparisons. For example, in this case, it will output:

Output:

10 is less than 20
10 is not equal to 20
10 is less than or equal to 20