3,343 瀏覽數

Bash Shell Script – read

下面是 read 可以加的參數,他們代表什麼意思!

測試環境為 Ubuntu 16.04 x64

read [-ers] [-a aname] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-ufd] [name …]

-p prompt
最常用的參數,顯示後面提示字串(不帶換行符號) 並等待使用者 輸入字串直到接收到 Enter(new‐line).

root@ubuntu:~# read -p "Input your Name:" name
Input your Name:Ben
root@ubuntu:~# echo ${name}
Ben

-t timeout
如果在設定的時間內 未讀取任何的輸入行,這時候會 讀取超時並表示為失敗並返回,可應用在 if else fi 中.

root@ubuntu:~# read -t5 -p "Input your Name:" name
Input your Name:root@ubuntu:~# echo ${name}

root@ubuntu:~#

-d delim
剛剛使用 -p 會使用 Enter(new‐line) 來結束輸入,-d 可以自訂結束輸入字元,下面的範例使用 “.” 當作結束字元.

root@ubuntu:~# read -d "." -p "Input your Name:(end of .)" name
Input your Name:(end of .)Ben Sun.root@ubuntu:~# echo ${name}
Ben Sun

-s Silent mode
當使用者輸入字元時,不顯示其輸入內容.

root@ubuntu:~# read -s -p "Input your Name:" name
Input your Name:root@ubuntu:~# echo ${name}
Ben

-r
反斜線 “\” 會被認為是行的一部分. 不能連續使用 “\\”。

root@ubuntu:~# read -p "Input your Name:" name
Input your Name:Ben \ Ben
root@ubuntu:~# echo ${name}
Ben Ben
root@ubuntu:~# read -r -p "Input your Name:" name
Input your Name:Ben \ Ben 
root@ubuntu:~# echo ${name}
Ben \ Ben
root@ubuntu:~# read -p "Input your Name:" name
Input your Name:Ben \\ Ben
root@ubuntu:~# echo ${name}
Ben \ Ben

下面參數還沒使用過,有機會再補上去.
-a aname
The words are assigned to sequential indices of the array variable aname, starting at 0.aname is unset before any new values are assigned.Other name arguments are ignored.

-e
If the standard input is coming from a terminal, readline is used to obtain the line. Readline uses the current (or default, if line editing was not previously active) editing settings.

-i text
If readline is being used to read the line, text is placed into the editing buffer before editing begins.

-n nchars
read returns after reading nchars characters rather than waiting for a complete line of input, but honor a delimiter if fewer than nchars characters are read before the delimiter.

-N nchars
read returns after reading exactly nchars characters rather than waiting for a complete line of input, unless EOF is encountered or read times out. Delimiter characters encountered in the input are not treated specially and do not cause read to return until nchars characters are read.

-u fd Read input from file descriptor fd.
If no names are supplied, the line read is assigned to the variable REPLY. The return code is zero, unless end-of-file is encountered, read times out (in which case the return code is greater than 128), or an invalid file descriptor is supplied as the argument to -u.

發表迴響