无法理解shell脚本中的[-t 0]

ivqmmu1c  于 2022-12-19  发布在  Shell
关注(0)|答案(3)|浏览(313)

defunkt github用户使用的This browser gist以以下shell表达式开始

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
vuktfyat

vuktfyat1#

  • []调用test
  • -t使test测试文件描述符以查看它是否是终端
  • 0是STDIN的文件描述符。

这就是说

if STDIN is a terminal then ...

动机

我必须阅读整个脚本才能确定,但通常是因为脚本想做一些视觉上的光滑,如清除屏幕,或交互提示。如果你正在阅读管道,没有必要这样做。

详细信息

好吧,让我们来看看整个脚本:

# 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。

g0czyy6m

g0czyy6m2#

来自ksh手册(bash也是如此)。

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

因此文件描述符0是标准输入。
您的代码本质上会问,我们是在交互模式下运行,还是在批处理模式下运行。
希望这能帮上忙。

z4iuyo4d

z4iuyo4d3#

这对于检查shell脚本是由真实的的用户使用终端调用的还是由crontab或守护进程调用的非常有用(在这种情况下,stdin将不存在)。
if [ -t 0 ] ---〉〉如果连接了标准输入(通常是键盘)

相关问题