检查bash脚本中的用户输入错误 [英] Check user input for errors in bash script

查看:106
本文介绍了检查bash脚本中的用户输入错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请看下面的代码:

  echo "nhat and betah for each element 
        TIPS: 4 REAL NUMBER for each element(eg, 1.0 0.0 1.0 .1)"
  read -a nbh
  if [ ${#nbh[@]} -ne 4 ]
  then 
    echo "Wrong!! "
  fi

此错误检查(if循环)将终止该程序,如果我忘了给出4个元素。
有可能,而不是终止,给用户一次机会(又一次)?即基本上再次转到读-a nbh 行?

This error check (if loop) will terminate the program, if I forget to give exactly 4 elements. Is it possible, rather then terminating, give the user a chance again (and again)? i.e. basically go to the read -a nbh line again?

推荐答案

一个而这个条件不匹配可以使它:

#!/bin/bash

while [ ${#nbh[@]} -ne 4 ] <---- repeat until this is not true
do
  echo "nhat and betah for each element 
        TIPS: 4 REAL NUMBER for each element(eg, 1.0 0.0 1.0 .1)"
  read -a nbh
  if [ ${#nbh[@]} -ne 4 ]
  then 
    echo "Wrong!! "
  fi
done                       <---- finish while loop



测试



Test

$ ./script
nhat and betah for each element 
        TIPS: 4 REAL NUMBER for each element(eg, 1.0 0.0 1.0 .1)
2 3
Wrong!! 
nhat and betah for each element 
        TIPS: 4 REAL NUMBER for each element(eg, 1.0 0.0 1.0 .1)
2 3 5 6
$

这篇关于检查bash脚本中的用户输入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆