日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Linux命令之read命令

發布時間:2023/12/20 46 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Linux命令之read命令 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、命令簡介

??Linux read命令用于從標準輸入讀取數值。read 內部命令被用來從標準輸入讀取單行數據。這個命令可以用來讀取鍵盤輸入,當使用重定向的時候,可以讀取文件中的一行數據。可以直接在命令行下直接,但常用于在shell腳本中輸入自定義變量值。

二、使用示例

0、直接執行

[root@test1 scripts]# read
this is a test

1、-p參數給定輸入提示

  • shell腳本

#!/bin/bash
read -p “輸入姓名:” name
echo “你輸入的姓名是:$name”
exit 0

  • 執行結果

[root@test1 scripts]# sh readshow.sh
輸入姓名:吳先生
你輸入的姓名是:吳先生

2、-s參數隱藏輸入內容

  • shell腳本

#!/bin/bash

read -s -p “輸入密碼:” passwd
echo -e “\n你輸入的密碼是:$passwd”
exit 0

  • 執行結果

[root@test1 scripts]# sh readshow.sh
輸入密碼:
你輸入的密碼是:Test123

3、-t參數指定等待輸入秒數

  • shell腳本

#!/bin/bash

if read -t 5 -p “輸入姓名:” name
then
echo “你輸入的姓名是 $name”
else
echo -e “\n抱歉,你輸入超時了。”
fi
exit 0

  • 執行結果

[root@test1 scripts]# sh readshow.sh
輸入姓名:
抱歉,你輸入超時了。

4、-n參數控制輸入字符,達到數目自動結束輸入

  • shell腳本

#!/bin/bash

read -n1 -p “Do you want to continue [Y/N]?” answer
case $answer in
Y | y)
echo -e “\nfine ,continue”;;
N | n)
echo -e “\nok,good bye”;;
*)
echo -e “\nerror choice”;;
esac
exit 0

  • 執行結果

[root@test1 scripts]# sh readshow.sh
Do you want to continue [Y/N]?y
fine ,continue
[root@test1 scripts]# sh readshow.sh
Do you want to continue [Y/N]?N
ok,good bye
[root@test1 scripts]# sh readshow.sh
Do you want to continue [Y/N]?1
error choice

5、讀取文件

  • shell腳本

[root@test1 scripts]# cat name.list
wuhs
sunru
bluesky
[root@test1 scripts]# cat readshow.sh
#!/bin/bash
\
count=1
cat name.list | while read line # cat命令的輸出作為read命令的輸入,read讀到>的值放在line中
do
echo -e “Line $count:$line”
count=$[ $count + 1 ] # 注意中括號中的空格。
done
exit 0

  • 執行結果

[root@test1 scripts]# sh readshow.sh
Line 1:wuhs
Line 2:sunru
Line 3:bluesky

三、命令語法及參數說明

1、命令語法

用法:: read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name …]

2、參數說明

  • -a 后跟一個變量,該變量會被認為是個數組,然后給其賦值,默認是以空格為分割符。
  • -d 后面跟一個標志符,其實只有其后的第一個字符有用,作為結束的標志。
  • -p 后面跟提示信息,即在輸入前打印提示信息。
  • -e 在輸入的時候可以使用命令補全功能。
  • -n 后跟一個數字,定義輸入文本的長度,很實用。
  • -r 屏蔽\,如果沒有該選項,則\作為一個轉義字符,有的話 \就是個正常的字符了。
  • -s 屏蔽回顯,在輸入字符時不再屏幕上顯示,例如login時輸入密碼。
  • -t 后面跟秒數,定義輸入字符的等待時間。
  • -u 后面跟fd,從文件描述符中讀入,該文件描述符可以是exec新開啟的。

總結

以上是生活随笔為你收集整理的Linux命令之read命令的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。