循环执行脚本的特定部分,直到满足特定要求

循环执行脚本的特定部分,直到满足特定要求

有什么方法可以让我循环遍历脚本的特定部分,直到设置特定变量为止?

我的意思是,我有这样的东西:

#!/bin/bash

# Check if sudo
if [ $UID -ne 0 ]; then
        echo "You have to run this as sudo" 1>&2
        exit 1
fi

# Get the date for the check
read -p "Please input a date, format 'Jan 12': " chosendate

# Get the time for the check
read -p "Please input the time, format '13:55', leave blank for no time: " chosentime

# Get last results based on input
gotresults=$(last |grep "$chosendate $chosentime" |awk '{print $1" " $5" " $6" " $7" " $9}')

if [[ $(echo "$gotresults"|wc -l) -ne 1 ]]; then
        echo "There are multiple entries corresponding to your input"
        echo
        echo "$gotresults"
        echo
read -p "Please select which entry you desire by typing in the time: " chosentime
        echo "$gotresults" |grep $chosentime
else
        echo "$gotresults"
fi

我想用这样的东西替换它:

#!/bin/bash

# Check if sudo
if [ $UID -ne 0 ]; then
        echo "You have to run this as sudo" 1>&2
        exit 1
fi

**FLAG1**
# Get the date for the check
read -p "Please input a date, format 'Jan 12': " chosendate

# Get the time for the check
read -p "Please input the time, format '13:55', leave blank for no time: " chosentime

# Get last results based on input
gotresults=$(last |grep "$chosendate $chosentime" |awk '{print $1" " $5" " $6" " $7" " $9}')

if [[ $(echo "$gotresults"|wc -l) -ne 1 ]]; then
        echo "There are multiple entries corresponding to your input"
        echo
        echo "$gotresults"
        echo
        echo "Please select a date/time that only returns one value"
        **GO TO FLAG1**

else
        echo "$gotresults"
fi

这样我就可以循环遍历这一部分(读取用户输入,然后执行操作),直到根据用户输入仅返回一个值。

我认为这可以通过“for”循环实现,但如果存在这样的东西,我会发现它更容易(我认为这个系统是在我曾经使用的某种程序中实现的)。

我更喜欢我提到的 FLAG 和 GO TO FLAG 系统的原因是,我可以在整个脚本中随时返回到标志,并且我可以更好地控制脚本的流程。因此,我可以将 FLAG1 放在某处,然后在脚本的多个部分(而不仅仅是一个部分)中转到 FLAG1,这对于 for 循环来说很难做到。

答案1

仅使用问题中的脚本我可能会做类似的事情(暂时忽略其他潜在的改进)

 have_results=0
 while [[ $have_results -eq 0 ]]; do
     read -p "Please input a date, format 'Jan 12': " chosendate
     read -p "Please input the time, format '13:55', leave blank for no time: " chosentime

     gotresults=$(last |grep "$chosendate $chosentime" |awk '{print $1" " $5" " $6" " $7" " $9}')

    if [[ $(echo "$gotresults"|wc -l) -ne 1 ]]; then
        echo "Please select a date/time that only returns one value"
    else
        have_results=1
    fi
done

相关内容