Join Whatsapp Channel for Ignou latest updates JOIN NOW

Write a shell script program to perform all Arithmetic Operations using Command line arguments.(b) Write a shell script program to search whether element is present is in the list or not and also display its position in the list

Sure, here are the shell scripts for the tasks:

(a) Shell script to perform all Arithmetic Operations using Command line arguments:

#!/bin/bash

# Check if the number of arguments is not equal to 3
if [ $# -ne 3 ]; then
    echo "Usage: $0 <number1> <operator> <number2>"
    exit 1
fi

num1=$1
operator=$2
num2=$3

# Perform arithmetic operation based on the operator
case $operator in
    +)
        result=$(echo "$num1 + $num2" | bc)
        ;;
    -)
        result=$(echo "$num1 - $num2" | bc)
        ;;
    *)
        echo "Invalid operator: $operator"
        exit 1
        ;;
esac

echo "Result: $result"

Save this script as arithmetic_operations.sh and make it executable using the command chmod +x arithmetic_operations.sh.

You can then run the script with three arguments, like so:

./arithmetic_operations.sh 5 + 3

(b) Shell script program to search whether an element is present in the list or not and also display its position in the list:

#!/bin/bash

# Check if the number of arguments is not equal to 2
if [ $# -lt 2 ]; then
    echo "Usage: $0 <element_to_search> <list_of_elements>"
    exit 1
fi

element_to_search=$1
shift
elements=("$@")

position=0
found=false

# Iterate through the elements and search for the element
for element in "${elements[@]}"; do
    ((position++))
    if [ "$element" == "$element_to_search" ]; then
        found=true
        break
    fi
done

# Check if the element is found or not
if $found; then
    echo "Element '$element_to_search' found at position $position"
else
    echo "Element '$element_to_search' not found in the list"
fi

Save this script as search_element.sh and make it executable using the command chmod +x search_element.sh.

You can then run the script with the element to search for followed by the list of elements, like so:

./search_element.sh 5 1 2 3 4 5

This will search for the element ‘5’ in the list ‘1 2 3 4 5’ and display its position if found.

error: Content is protected !!