Home > Mobile >  How to simplified the code using loop in shell script?
How to simplified the code using loop in shell script?

Time:06-09

I'm new to Shell Scripting and created the code below, but I need to simplify the code using a loop or something to make it shorter. When I tried to use the for loop in my code, I couldn't get the correct output, so I used an if-else statement. So the program should prompt the user to enter 10 numbers, assign them equally to two arrays, and compare each element to the others.

#!/bin/bash

declare -a Array1
declare -a Array2

for ((i = 1; i<3; i  ))
do
echo "(Array $i)"

for((j = 0; j<5; j  ))
do

read -p "Enter number: " num

if [ $i == 1 ];
then
Array1[$j]="$num"
else
Array2[$j]="$num"
fi

done
done

echo "(Array 1) ${Array1[@]}"
echo "(Array 2) ${Array2[@]}"

arr11=${Array1[0]}
arr12=${Array1[1]}
arr13=${Array1[2]}
arr14=${Array1[3]}
arr15=${Array1[4]}

arr25=${Array2[0]}
arr24=${Array2[1]}
arr23=${Array2[2]}
arr22=${Array2[3]}
arr21=${Array2[4]}

if(( $arr11 > $arr21 ));then
echo "$arr11 > $arr21"
elif (( $arr11 < $arr21 ));then
echo "$arr11 < $arr21"
else
echo "$arr11 == $arr21"
fi

if(( $arr12 > $arr22 ));then
echo "$arr12 > $arr22"
elif (( $arr12 < $arr22 ));then
echo "$arr12 < $arr22"
else
echo "$arr12 == $arr22"
fi

if(( $arr13 > $arr23 ));then
echo "$arr13 > $arr23"
elif (( $arr13 < $arr23 ));then
echo "$arr13 < $arr23"
else
echo "$arr13 == $arr23"
fi

if(( $arr14 > $arr24 ));then
echo "$arr14 > $arr24"
elif (( $arr14 < $arr24 ));then
echo "$arr14 < $arr24"
else
echo "$arr14 == $arr24"
fi

if(( $arr15 > $arr25 ));then
echo "$arr15 > $arr25"
elif (( $arr15 < $arr25 ));then
echo "$arr15 < $arr25"
else
echo "$arr15 == $arr25"
fi

CodePudding user response:

you can use single for loop for the main processing in your code after you've taken the input from user. Here's the code:

#!/bin/bash

declare -a Array1
declare -a Array2

for ((i = 1; i<3; i  ))
do
echo "(Array $i)"

for((j = 0; j<5; j  ))
do

read -p "Enter number: " num

if [ $i == 1 ];
then
Array1[$j]="$num"
else
Array2[$j]="$num"
fi

done
done

echo "(Array 1) ${Array1[@]}"
echo "(Array 2) ${Array2[@]}"

for ((j = 0; j<5; j  ))
do
if(( Array1[$j] > Array2[4-$j] ));then
echo "${Array1[$j]} > ${Array2[4-$j]}"
elif (( Array1[$j] < Array2[4-$j] ));then
echo "${Array1[$j]} < ${Array2[4-$j]}"
else
echo "${Array1[$j]} = ${Array2[4-$j]}"
fi
done
  • Related