【问题标题】:Write a bash loop using loop使用循环编写 bash 循环
【发布时间】:2014-11-17 01:05:13
【问题描述】:

如何编写bash脚本,如果输入空值“”,或者1和2以外的其他值不会结束脚本,并且会让用户租用1或2。如果用户输入错误,会让用户租用租客。

    echo Press 1 for services and 2 for chkconfig?
    echo -n "Please input yes or no: "
    read ANS
if [ $ANS != "" ];

if [ $ANS == 1 ];
then
   service vsftpd status
elif [ $ANS == 2 ];
then
 service vsftpd status
else
echo please input 1 oe 2

fi
~

【问题讨论】:

    标签: linux bash loops


    【解决方案1】:

    试试这个:

    while true
    do
        echo -n "Enter 1 for status, 2 for chkconfig, or q to quit: "
        read ANS
        if [ "$ANS" = q ]
        then
           break
        elif [ "$ANS" = 1 ]
        then
           service vsftpd status
           break
        elif [ "$ANS" = 2 ]
        then
           service vsftpd chkconfig
           break
        else
           echo "Invalid input.  Try again."
        fi
    done
    

    注意事项:

    • 为了让用户在第一次未能输入正确答案时重新输入答案,代码被放置在while 循环中。当给出满意的答案时,使用break 命令退出循环。没有满意的答案,循环重复,直到输入一个。

    • 我添加了一个“退出”选项,因为这是用户通常会坚持的。

    • [ 样式测试中,相等的符号是=。一些 shell 会在这里接受==,但其他 shell 会被它窒息。另一方面,如果使用 [[ 样式测试(需要 bash),则 == 是正确的相等符号。

    • [ 样式测试中,将shell 变量放在双引号中很重要。因此,将[ $ANS = 1 ] 替换为[ "$ANS" = 1 ]。否则,如果用户只输入了输入,则ANS 将为空并且脚本将因错误而失败。对于[[ 样式测试,不需要引号。

    【讨论】:

      【解决方案2】:

      这将一直询问,直到您输入“1”或“2”。

      #!/bin/sh
      while [ 1 ]; 
      do
      echo Please enter 1 or 2:
      read ANS;
          if [ "$ANS" = "1" ]; then echo You entered 1!; break; fi
          if [ "$ANS" = "2" ]; then echo You entered 2!; break; fi
      done
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-11-28
        • 2010-09-08
        • 2021-04-07
        • 2014-09-03
        • 1970-01-01
        • 1970-01-01
        • 2016-05-13
        相关资源
        最近更新 更多