Open In App

Bash shell script to find out the largest value from given command line arguments

Write a shell script to find out the largest value from the given number of command-line arguments.

Example:



Special variables in bash:



$@- All arguments.
$#- Number of arguments.
$0- Filename.
$1, $2, $3, $4 ... - Specific arguments.

Approach




#Check if the number of arguments passed is zero
if [ "$#" = 0 ]
then
    #Script exits if no
    #arguments passed
    echo "No arguments passed."
    exit 1
fi
  
#Initialize maxEle with 
#the first argument
maxEle=$1
  
#Loop that compares maxEle with the 
#passed arguments and updates it
for arg in "$@"
do
    if [ "$arg" -gt "$maxEle" ]
    then
        maxEle=$arg
    fi
done
echo "Largest value among the arguments passed is: $maxEle"

Article Tags :