首页 > 解决方案 > Bash脚本循环分析

问题描述

我必须对这个 bash 脚本做什么才能让它重复“输入学生姓名以获得他们的分数:”并在用户再次输入姓名时输入空格时停止?目前它只接受名称并返回一次分数。我正在尝试使用while循环来重复“while continue=0”的过程。我知道这很简单,我只是卡住了。

这是我的代码

continue=0
while [[ continue -eq 0 ]]; do
            echo " "                                                                                                                
            echo "Enter a student's name to get their score: "
            read sName
            echo "Searching for $sName's score"
            length=${#names[@]}
            start=0
            end=$((length -1))
            while [[ $start -le $end ]]; do
                    mid=$((start + ((end - start)/2)))
                    midName=${names[mid]}
            if [[ $midName > $sName ]]; then
                    end=$((end-mid-1))
            elif [[ $midName < $sName ]]; then
                    start=$((mid+1))
            else
                    echo "${scores[$mid]}"
                    exit 0
            fi
    done
done

标签: linuxbashshellcommand-linescripting

解决方案


这是一个简化示例,说明如何实现您想要的:

#!/bin/bash

while :
do
   echo "Enter a student's name to get their score: "
   read name

   if [[ -z $name ]]
   then
      break
   fi

   # got name, continue processing

done

推荐阅读