defunkt github用户的浏览器要点开始于此shell表达式
if [ -t 0 ]; then ...
Run Code Online (Sandbox Code Playgroud)
这行代码的含义是什么?
更新:您还能解释为什么我需要做此检查之前执行其他任何操作吗?
为了完整起见,这是整个小脚本(它允许将文本通过管道传递到默认浏览器):
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
Run Code Online (Sandbox Code Playgroud)
[并]调用test-t使test测试成为文件描述符,以查看它是否是终端0 是STDIN的文件描述符。所以说
if STDIN is a terminal then ...
Run Code Online (Sandbox Code Playgroud)
我必须阅读整个脚本才能确定,但这通常是因为该脚本想要做一些视觉上很平滑的事情,例如清除屏幕或交互式提示。如果您正在阅读管道,那么这样做是没有意义的。
好吧,让我们检查一下整个脚本:
# 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
Run Code Online (Sandbox Code Playgroud)
因此,这是在检查您是否在终端上。如果是这样,它将查找带有文件名或URL的参数。如果不是终端,则尝试将输入显示为html。