read 命令詳解

xie仗劍天涯發表於2017-04-04

read 命令從標準輸入中讀取一行,並把輸入行的每個欄位的值指定給 shell 變數

語法選項

-p  read –p “提示語句”,則螢幕就會輸出提示語句,等待輸入,並將輸入儲存在REPLY中
-n  read –n 個數
-t  read –t 時間
-s  read -s 選項能夠使read命令中輸入的資料不顯示在監視器上

例子

  1. 從標準輸入讀取輸入並賦值給變數
[xiess@layzj022301 ~]$ read readfile
hello,world!!welcome to shell
[xiess@layzj022301 ~]$ echo $readfile
hello,world!!welcome to shell
[xiess@layzj022301 ~]$
  1. 等待一組輸入,每個單詞之間使用空格隔開,直到回車結束,並分別將單詞依次賦值給這三個讀入變數。
[xiess@layzj022301 ~]$ read frist second third
the_one the_two the_three
[xiess@layzj022301 ~]$ echo "$frist" "$second" "$third"
the_one the_two the_three
[xiess@layzj022301 ~]$
  1. REPLY示例
[xiess@layzj022301 ~]$ read -p "Enter your name: "
Enter your name: admin_xiess
[xiess@layzj022301 ~]$ echo $REPLY
admin_xiess
[xiess@layzj022301 ~]$
  1. 關閉顯示
[root@cinder01 ~]# cat readfile.sh 
#!/bin/bash
read -s -p "Enter your password: " password
echo
echo "your password is $password"
[root@cinder01 ~]# chmod a+x readfile.sh 
[root@cinder01 ~]# sh readfile.sh 
Enter your password: 
your password is 123456