Легко сделать, просто полностью удалив переменную int
и заменив ее на count
, которую вы уже увеличиваете в пределах l oop, например,
sumsq=0 #sum of squares
count=0 #Running count of numbers passed as arguments
while (( $# != 0 )); do
numbers[$count]=$1 #Assigns arguments to integers array
square=$(($1*$1)) #Operation to square argument first arg by itself
squares[$count]=$square #Square of each argument
sumsq=$((sumsq + square)) #Add square to total
count=$((count+1)) #Increment count
shift #Remove the used argument
done
Пример использования / Вывод
Внесение изменений выше:
$ bash squares.sh 1 2 3 4
The squares are 1 4 9 16
The sum of the squares is 30
(нет, вы не такие в программировании, это одна из проблем, на которую новые сценаристы могут смотреть часами и не видеть - и почему полезно работать с bash -x scriptname
для отладки)
Обновление после комментария Re: Сложность
Выше я только опубликовал необходимые изменения. Если это не работает для вас, то я подозреваю, что где-то опечатка. Вот полный скрипт, который вы можете просто сохранить и запустить:
#!/bin/bash
if [ $# = 0 ]
then
echo "Enter some numbers"
exit 1
fi
sumsq=0 #sum of squares
count=0 #Running count of numbers passed as arguments
while (( $# != 0 )); do
numbers[$count]=$1 #Assigns arguments to integers array
square=$(($1*$1)) #Operation to square argument first arg by itself
squares[$count]=$square #Square of each argument
sumsq=$((sumsq + square)) #Add square to total
count=$((count+1)) #Increment count
shift #Remove the used argument
done
echo "The squares are ${squares[@]}"
echo "The sum of the squares is $sumsq"
exit 0
В соответствии с приведенным выше примером запустите скрипт как:
bash squares.sh 1 2 3 4
(замените squares.sh
на любое имя, которое вы дал файл) Если у вас есть какие-либо проблемы, дайте мне знать, потому что это работает довольно хорошо, например,
bash squares.sh 1 2 3 4 5 6 7 8 9
The squares are 1 4 9 16 25 36 49 64 81
The sum of the squares is 285