1. 程式人生 > >Linux 基礎教程 45-read命令

Linux 基礎教程 45-read命令

技術 -i 分享圖片 ech adt clas 喜歡 body 技術分享

基本用法

? ? read命令主要用於從標準輸入讀取內容或從文件中讀取內容,並把信息保存到變量中。其常用用法如下所示:

read [選項] [文件]
選項 解釋
-a array 將內容讀取到數值中,變量默認為數組且以空格做為分割符
-d delimiter 遇到指定的字符即停止讀取
-n nchars 指定最多可以讀入的字符數,即定義輸入文本的長度
-r 屏蔽轉義符
-p prompt 顯示提示信息
-s 靜默模式,在輸入字符時不在終端中顯示,常用於密碼輸入等
-t timeout 指定超時時間
-u FD 從文件描述符中讀入,該FD可以由exec開啟

用法示例

1、從標準輸入讀入

[root@localhost test]# cat read.sh
#!/bin/bash
echo -n "Please input your name:"
read name
echo "Hello $name"
[root@localhost test]# bash read.sh
Please input your name:Jack
Hello Jack

2、指定顯示信息從標準輸入讀入

[root@localhost test]# cat read.sh
#!/bin/bash
# echo -n "Please input your name:"
read -p "Please input your name:" name
# read name
echo "Hello $name"
[root@localhost test]# bash read.sh
Please input your name:Jack
Hello Jack

在以上示例中,read是一次可以接受多個參數的,如下所示:

read -p "Please input your name:" firstName secondName lastName

但需要註意的事項如下:

  • 如果輸入的數據少於變量個數,則多余的變量不會獲取到數據,即變量值為空
  • 如果輸入的數據多於變量個數,則超出的數據將全部賦給最後一個變量
  • 如果在read命令後面沒有定義任何變量,腳本在執行時,如果用戶輸入數據,此時數據則保存到環境變量$REPLY

3、指定超時時間

[root@localhost test]# cat read.sh
#!/bin/bash
if read -t 3 -p "Please input your name:" firstName secondName lastName
then
  echo "variable is $firstName - $secondName - $lastName"
else
   echo -e  "\ntimeout\n"
fi
[root@localhost test]# bash read.sh
Please input your name:
timeout

4、從指定文件中讀取內容

[root@localhost test]# cat -n test.txt
     1  this is test text.
     2  this is second line.
     3  Hello world
     4  C# Main
     5  Python
# 使用-u選項
[root@localhost test]# cat readtest.sh
#!/bin/bash
exec 5< ~/test/test.txt
count=0
while read -u 5 var
do
 let count=$count+1
 echo "Line $count is $var"
done
echo "Total line count is $count"
exec 5<&-
[root@localhost test]# bash readtest.sh
Line 1 is this is test text.
Line 2 is this is second line.
Line 3 is Hello world
Line 4 is C# Main
Line 5 is Python
Total line count is 5
# 使用管道
[root@localhost test]# cat readtest.sh
#!/bin/bash
count=1
cat ~/test/test.txt |  while read line
do
 echo "Current line $count - $line "
 let count=$count+1
done
echo "Total line count is $count"
[root@localhost test]# bash readtest.sh
Current line 1 - this is test text.
Current line 2 - this is second line.
Current line 3 - Hello world
Current line 4 - C# Main
Current line 5 - Python
Total line count is 1
# 使用重定向
[root@localhost test]# cat readtest.sh
#!/bin/bash
count=0
while read line
do
 let count=$count+1
 echo "Current line $count - $line "
done < ~/test/test.txt
echo "Total line count is $count"
[root@localhost test]# bash readtest.sh
Current line 1 - this is test text.
Current line 2 - this is second line.
Current line 3 - Hello world
Current line 4 - C# Main
Current line 5 - Python
Total line count is 5

本文同步在微信訂閱號上發布,如各位小夥伴們喜歡我的文章,也可以關註我的微信訂閱號:woaitest,或掃描下面的二維碼添加關註:
技術分享圖片

Linux 基礎教程 45-read命令