• [shell基础]——read命令


    read命令:在shell中主要用于读取输入、变量、文本

    1. 接受标准输入(键盘)的输入,并将输入的数据赋值给设置的变量
         【按回车键——表示输入完毕】
         【若输入的数据多于设置的变量数,则将多出的部分全部赋给最后一个变量】
         【若没有设置变量,则将输入的数据赋给环境变量REPLAY】

    #!/bin/bash
    echo -n "Enter your name:"
    read name1 name2
    echo hello,$name1,$name2
    
    # ./read.sh 
    Enter your name:taeyeon jessica
    hello,taeyeon,jessica

    2.  -p 在read命令行中直接print一个提示

    #!/bin/bash
    read  -p  "Enter your name:" name1  name2
    echo hello,$name1,$name2
    
    # ./read.sh 
    Enter your name:taeyeon jessica
    hello,taeyeon,jessica

     3.  -t 实现计时输入。指定read命令等待输入的秒数。

    #!/bin/bash
    if read -t 5  -p  "Enter your name:" name    ## -p后要直接接提示语,注意多选项时怎么用
    then
       echo hello,$name
    else
       echo -e "
    sorry,too slow"
    fi
    exit 0
    
    # ./read.sh 
    Enter your name:jelly
    hello,jelly
    # ./read.sh 
    Enter your name:
    sorry,too slow

    4. -n   实现计数输入。指定read命令接受输入的数据长度。当超过这个长度,无论按任意键都表示输入结束。
        -n1 表示接受一个字符的输入就退出,不需要按回车键

    #!/bin/bash
    read -n1 -p "Do you want to continue [y/n]?" y1
    case $y1 in
        Y|y) echo -e "
    ok,continue!";;
        N|n) echo -e "
    ok,stop!";;
        *)   echo -e "
    error choice!"
    esac
    
    # ./read.sh 
    Do you want to continue [y/n]?y
    ok,continue!
    # ./read.sh 
    Do you want to continue [y/n]?n
    ok,stop!
    # ./read.sh 
    Do you want to continue [y/n]?p
    error choice!

    5. -s 实现隐藏输入。实际是使得输入的数据和背景色一致。常用于接受密码输入时。

    #!/bin/bash
    read -s  -p "Enter you password:" passwd
    echo -e "
    "
    echo "haha,your passwd is:$passwd"
    
    [root@sxjy ~]# ./read.sh 
    Enter you password:
                                                    #看不见吧...
    haha,your passwd is:aixocm

    6. 读取文本中的数据作为read的输入

    #!/bin/bash
    count=1
    cat  gg.txt  | while  read  name   #逐行读取gg.txt文本中的内容给变量name  
    do
            echo "$count:$name"
            count=$[$count+1]
    done
    
    # ./read.sh
    1:taeyeon
    2:jessica
    3:sunny
  • 相关阅读:
    nyoj58 最少步数
    oj2787 算24
    一位ACMer过来人的心得
    hdu递推公式水题
    nyoj20 吝啬的国度
    hdu1421 搬寝室
    全排列生成算法:next_permutation
    hdu2544 最短路
    poj1691 Painting A Board
    hdu1274 展开字符串
  • 原文地址:https://www.cnblogs.com/snsdzjlz320/p/5598977.html
Copyright © 2020-2023  润新知