2012-01-20 45 views
1

內部的browser要旨由德芬克特github上用戶與該殼表達無法瞭解[-t 0]殼腳本

if [ -t 0 ]; then ... 

什麼是這行代碼的含義開始?

更新:你能解釋爲什麼我需要這個檢查之前做任何事情嗎?

爲了完整起見,這裏是整個小腳本(它允許管文本的默認瀏覽器):

if [ -t 0 ]; then 
    if [ -n "$1" ]; then 
    open $1 
    else 
    cat <<usage 
Usage: browser 
     pipe html to a browser 

$ echo '<h1>hi mom!</h1>' | browser 
$ ron -5 man/rip.5.ron | browser 
usage 

fi 
else 
    f="/tmp/browser.$RANDOM.html" 
    cat /dev/stdin > $f 
    open $f 
fi 

回答

4

「[]」調用測試

-t使得測試測試文件描述符以查看它是否爲終端

0是STDIN的文件描述符。

這樣說

if STDIN is a terminal then ... 

更新

我不得不讀取整個劇本就知道肯定,但通常是因爲腳本要做些什麼視覺上光滑的像清除屏幕或交互式提示。如果你在管道上,這樣做沒有意義。

更新2

好吧,讓我們來看看整個腳本:

# If this has a terminal for STDIN 
if [ -t 0 ]; then 
    # then if argument 1 is not empty 
    if [ -n "$1" ]; then 
    # then open whatever is named by the argument 
    open $1 
    else 
    # otherwise send the usage message to STDOUT 
    cat <<usage 
Usage: browser 
     pipe html to a browser 

$ echo '<h1>hi mom!</h1>' | browser 
$ ron -5 man/rip.5.ron | browser 
usage 
#That's the end of the usage message; the '<<usage' 
#makes this a "here" document. 
fi # end if -n $1 
else 
    # This is NOT a terminal now 
    # create a file in /tmp with the name 
    # "browser."<some random number>".html" 
    f="/tmp/browser.$RANDOM.html" 
    # copy the contents of whatever IS on stdin to that file 
    cat /dev/stdin > $f 
    # open that file. 
    open $f 
fi 

所以這是檢查,看看如果你是一個終端上;如果是這樣,它會查找帶有文件名或URL的參數。如果不是終端,則它會嘗試將輸入顯示爲html。

+0

你可以添加**爲什麼**需要它? THX – microspino

1

從ksh手冊(對於bash也是如此)。

-t fildescriptor  
    True, if file descriptor number fildes is open and associated with a terminal device. 

所以文件描述符0是std的輸入。

您的代碼基本上是以交互模式運行,還是處於批處理模式。

我希望這會有所幫助。

+0

@shelter爲什麼我必須在腳本內區分交互和批處理? – microspino

+0

看看在這個'if [-t 0];之間定義的塊內發生了什麼?那麼......這段代碼在做什麼......;這就是原因。您可能正在尋找僅用於加載別名和函數的rc文件,這些文件僅在命令行中有用。 (這是該測試最常見的用法)。與從crontab運行腳本時相比,不會有與腳本關聯的終端。祝你好運。 – shellter