哨兵值 -1 的 shell 脚本

bre*_*ren -1 shell scripting shell-script

#!/bin/bash

set -x

count=0
number=0
loops=0
average=0

read -p " Please enter a number between 1 and 100? " number

while [ $count -lt $number ]
done

average=`expr $score / $number`

echo $average
Run Code Online (Sandbox Code Playgroud)

创建一个 shell 程序,要求用户输入一个 1 到 100 之间的数字,一旦输入了 -1 的标记值,就存在循环。程序必须保留所有循环迭代的计数、总计数以及程序结束后的平均次数。

我猜我必须使用一个if语句,但我不太知道如何使用。

Hax*_*iel 5

可能有更有效的方法可以做到这一点,但以下脚本应该可以完成这项工作:

#!/bin/bash

loops=0
sum=0

# Loop forever
while true; do
    read -p "Please enter a number between 1 and 100: " input

    # Check for the exit condition.
    if [[ $input -eq -1 ]]; then
        break
    fi

    # Use a regex to check that input is a one-digit, two-digit or three-digit number and that the input is in [1,100] .
    if [[ $input =~ ^[0-9]{1,3}$ && $input -gt 0 && $input -le 100 ]]; then
        # Use arithmetic expansion to increment loop counter and add the new input to sum.
        ((loops++))
        ((sum += input))
    else
        echo "Invalid input. Skipping..."
    fi

done

# For the edge case where there is no valid input.
if [[ $loops -eq 0 ]]; then
    echo "Average undefined - no valid input."
    exit
fi

average=$((sum/loops))

echo "Average: $average"
Run Code Online (Sandbox Code Playgroud)

示例运行:

Please enter a number between 1 and 100: 2
Please enter a number between 1 and 100: 3
Please enter a number between 1 and 100: 4
Please enter a number between 1 and 100: 5
Please enter a number between 1 and 100: 6
Please enter a number between 1 and 100: -1
Average: 4
Run Code Online (Sandbox Code Playgroud)