zoukankan      html  css  js  c++  java
  • linux shell获取用户输入

    一、获取用户输入
    1、基本读取
    read命令接收标准输入的输入,或其它文件描述符的输入。得到输入后,read命令将数据输入放入一个标准变量中。
    [root@rac2 ~]# cat t8.sh
    #!/bin/bash
    #testing the read command
    echo -n "enter your name:" ---:-n用于允许用户在字符串后面立即输入数据,而不是在下一行输入。
    read name
    echo "hello $name ,welcome to my program."
    [root@rac2 ~]# ./t8.sh
    enter your name:zhou
    hello zhou ,welcome to my program.
    read命令的-p选项,允许在read命令行中直接指定一个提示:
    [root@rac2 ~]# cat t9.sh
    #!/bin/bash
    #testing the read -p option
    read -p "please enter your age:" age ---age与前面必须有空格
    echo "your age is $age"
    [root@rac2 ~]# ./t9.sh
    please enter your age:10
    your age is 10
    2、在read命令中也可以不指定变量,如果不指定变量,那么read命令会将接收到的数据防止在环境变量REPLAY中
    [root@rac2 ~]# cat t10.sh
    #!/bin/bash
    #tesing the replay environment variable
    read -p "enter a number:"
    factorial=1
    for (( count=1; count<=$REPLY; count++ ))
    do
    factorial=$[ $factorial * $count ]
    done
    echo "the factorial of $REPLY is $factorial"
    [root@rac2 ~]# ./t10.sh
    enter a number:5
    the factorial of 5 is 120
    3、计时
    -t选项指定read命令等待输入的秒数。当计时器计时数满时,read命令返回一个非零退出状态
    [root@rac2 ~]# cat t11.sh
    #!/bin/bash
    #timing the data entry
    if read -t 5 -p "please enter your name:" name
    then
    echo "hello $name ,welcome to my script"
    else
    echo "sorry ,tow slow!"
    fi
    [root@rac2 ~]# ./t11.sh
    please enter your name:zhou
    hello zhou ,welcome to my script
    [root@rac2 ~]# ./t11.sh
    please enter your name:sorry ,tow slow!
    4、默读
    有时候需要脚本用户进行输入,但不希望输入的数据显示在监视器上,(实际上是显示的只是read命令将文本颜色设置为与背景相同的了)。
    [root@rac2 ~]# cat t12.sh
    #!/bin/bash
    #hiding input data from the monitor
    read -s -p "enter your password:" pass
    echo "is your password really $pass?"
    [root@rac2 ~]# ./t12.sh
    enter your password:is your password really 12345?
    5、读取文件
    每调用一次read命令都会读取文件中的一行文本,当文件中没有可读的行时,read命令将以非零退出状态退出。
    [root@rac2 ~]# cat t13.sh
    #!/bin/bash
    count=1
    cat test | while read line
    do
    echo "line $count:$line"
    count=$[$count + 1]
    done
    [root@rac2 ~]# ./t13.sh
    line 1:zhou
    line 2:xiao
    line 3:zhou

  • 相关阅读:
    centos 安装docker-ce
    quartz.net .netcore 定时任务部署到linux
    c# 获取linux 磁盘信息
    nginx 安装
    async await 理解
    Remote side unexpectedly closed network connection
    centos 安装。net
    yum 操作
    centos7下安装mysql5.7
    git 本地仓库版本无法从远程更新到本地
  • 原文地址:https://www.cnblogs.com/zqifa/p/linux-shell-1.html
Copyright © 2011-2022 走看看