• shell_50.Linux获取用户输入_超时


    超时
    使用 read 命令时要当心。脚本可能会一直苦等着用户输入。如果不管是否有数据输入,脚
    本都必须继续执行,你可以用-t 选项来指定一个计时器。-t 选项会指定 read 命令等待输入的
    秒数。如果计时器超时,则 read 命令会返回非 0 退出状态码:

    1. $ cat asknametimed.sh 
    2. #!/bin/bash 
    3. # Using the read command with a timer 
    4. if read -t 5 -p "Enter your name: " name 
    5. then 
    6.     echo "Hello $name, welcome to my script." 
    7. else 
    8.     echo 
    9.     echo "Sorry, no longer waiting for name." 
    10. fi 
    11. exit 
    12. $ ./asknametimed.sh 
    13. Enter your name: Christine 
    14. Hello Christine, welcome to my script. 
    15. $ ./asknametimed.sh 
    16. Enter your name: 
    17. Sorry, no longer waiting for name. 
    18. $

    可以不对输入过程计时,而是让 read 命令统计输入的字符数。当字符数达到预设值时,
    就自动退出,将已输入的数据赋给变量:

    1. $ cat continueornot.sh 
    2. #!/bin/bash 
    3. # Using the read command for one character 
    4. read -n 1 -p "Do you want to continue [Y/N]? " answer 
    5. case $answer in 
    6.     Y | y) echo 
    7.         echo "Okay. Continue on...";; 
    8.     N | n) echo 
    9.     echo "Okay. Goodbye" 
    10.     exit;; 
    11. esac 
    12. echo "This is the end of the script." 
    13. exit 
    14. $ ./continueornot.sh
    15. Do you want to continue [Y/N]? Y
    16. Okay. Continue on... 
    17. This is the end of the script. 
    18. $ ./continueornot.sh 
    19. Do you want to continue [Y/N]? n
    20. Okay. Goodbye 
    21. $

  • 相关阅读:
    Mysql InnoDB Redo log
    Mac vsCode快捷键总结
    【JavaSE】重载和重写
    2310D的dll问题
    jenkins持续集成环境搭建
    关于安卓jsbridge的使用
    C语言——数组详解
    AS86汇编语法
    《软件方法》第1章2023版连载(03)建模工作流
    本地PHP搭建简单Imagewheel私人云图床,在外远程访问
  • 原文地址:https://blog.csdn.net/mmmmm168m/article/details/134047474