这个浏览器要点 https://gist.github.com/318247by defunkt github 用户以此 shell 表达式开始
if [ -t 0 ]; then ...
这行代码的含义是什么?
UPDATE:您还能解释一下为什么我在做其他事情之前需要进行此检查吗?
为了完整起见,这里是整个小脚本(它允许将文本通过管道传输到默认浏览器):
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
-
[
and ]
调用test
-
-t
使得test
测试文件描述符以查看它是否是终端
-
0
是 STDIN 的文件描述符。
所以说
if STDIN is a terminal then ...
动机
我必须阅读整个脚本才能确定,但通常是因为脚本想要执行一些视觉上流畅的操作,例如清除屏幕或交互式提示。如果你正在读取管道,那么这样做是没有意义的。
Detail
好的,让我们检查一下整个脚本:
# 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 的参数。如果它isn't终端,然后它尝试将输入显示为 html。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)