I need to calculate the biggest number in array size n.
Example: Users enter: 1 7 4 9
The biggest number is : 9
Simple but I'm really new on this on Shell/Bash! Anything will be helpful! Thanks!
#!/bin/bash
printf "\tEnter a list of numbers, with spaces: "
read -a ARRAY
BIG=$1
for i in ${!ARRAY[@]} ; do
if [ $i -gt $BIG ] ; then
BIG=$i
fi
done
echo "Largest number is $BIG"
You're right. That's the key.
Just for studying purposes, I've created two bash scripts using different for loop syntax for solving this problem.
Here we go:
#!/opt/local/bin/bash
# rod@wgo.com.br
# get the biggest number in an array of integers
declare -a list # array of integers
declare -i size # size of the array
declare -i biggest # biggest number of the array
declare -i current # current element of the array
read -a list -p "Enter each integer element separated by white spaces: "
size=${#list[@]}
biggest=${list[0]} # first element of the array is supposed to be the biggest one
for ((i=1; i<$size; i++)); do # loop through the array ( this syntax is kind of similar to the for loop used by the C programming language )
current=${list[$i]} # get the current element of the array. This way you don't have to worry too much about bash syntax for accessing elements is an array
if [ $current -gt $biggest ]; then
biggest=$current
fi
done
echo -e "\nThe biggest integer number in the array is: $biggest";
#!/opt/local/bin/bash
# rod@wgo.com.br
# get the biggest number in an array of integers
declare -a list # array of integers
declare -i biggest # biggest number of the array
declare -i current # current element of the array
read -a list -p "Enter each integer element separated by white spaces: "
size=${#list[@]}
biggest=${list[0]} # first element of the array is supposed to be the biggest one
for current in ${list[@]}; do # loop through the array
if [ $current -gt $biggest ]; then
biggest=$current
fi
done
echo -e "\nThe biggest integer number in the array is: $biggest";
Of course, there is more than a way for doing such things.
I suggest you give "Advanced Bash-Scripting Guide" a try. It's a really good and powerful book about Bash Scripting. You may download it for free here:
Unless it is for learning purposes, in this case there is no need for arrays.
BIG=0
printf "\tEnter a list of numbers, separated by spaces: "
read list
for i in $list; do
if [ $i -gt $BIG ]; then
BIG=$i
fi
done
printf "%s\n" "Largest number is $BIG"