[shell基礎]——read命令

Jelly_lyj發表於2017-03-18

 

read命令:在shell中主要用於讀取輸入、變數、文字

 

1. 接受標準輸入(鍵盤)的輸入,並將輸入的資料賦值給設定的變數
     【按Enter鍵——表示輸入完畢】
     【若輸入的資料多於設定的變數數,則將多出的部分全部賦給最後一個變數】
     【若沒有設定變數,則將輸入的資料賦給環境變數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 "\nsorry,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 表示接受一個字元的輸入就退出,不需要按Enter鍵

#!/bin/bash
read -n1 -p "Do you want to continue [y/n]?" y1
case $y1 in
    Y|y) echo -e "\nok,continue!";;
    N|n) echo -e "\nok,stop!";;
    *)   echo -e "\nerror 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 "\n"
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

 

相關文章