Multiple Read statements. Do not proceed until user input is given

陌路散爱 提交于 2021-01-29 14:43:37

问题


I have a few read statements. Im trying to figure out how to prevent the user from going to the next statement unless they have provided user input. I am having trouble wrapping my head around this. I have seen examples for a single read -p statement but can't seem to find an appropriate solution for multiple subsequent read statements.

     read -p " Write something: " var1
     read -p " Write something again: " var2
     read -p " write something a third time: " var3
 desired output
 Write something: #no input
 You have not entered anything. Please try again.
 Write something: computer
 Write something again

then proceed accordingly.


回答1:


Same as Cyrus posted but with a warning

until [[ "$var1" ]]; do
    read -p " Write something: " var1
    [[ "$var1" ]] || echo "You have not entered anything. Please try again."
done

And this will create all vars in one loop

vars=(var1 var2 var3)

for varname in ${vars[@]}; {
    until [[ "${!varname}" ]]; do
        read -p " Write something to $varname: " $varname
        [[ "${!varname}" ]] || echo "You have not entered anything. Please try again."
    done    
}

We can go further and use an array to store data

for i in {1..3}; {
    until [[ "${vars[$i]}" ]]; do
        read -p "Write something to var$i: " vars[$i]
        [[ "${vars[$i]}" ]] || echo "You have not entered anything. Please try again."
    done    
}



回答2:


With bash:

while [[ "$var1" = "" ]]; do read -p " Write something: " var1; done


来源:https://stackoverflow.com/questions/60390331/multiple-read-statements-do-not-proceed-until-user-input-is-given

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!