microspino
microspino

Reputation: 7781

Unable to understand [-t 0] inside shell script

This browser gist by defunkt github user starts with this shell expression

if [ -t 0 ]; then ...

What is the meaning of this line of code?

UPDATE: could you also explain why i need this check before doing anything else?

For the sake of completeness, here is the entire little script (it allow to pipe text to the default browser):

 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

Upvotes: 7

Views: 3855

Answers (3)

Charlie Martin
Charlie Martin

Reputation: 112424

  • [ and ] invokes test
  • -t makes the test test a file descriptor to see if it's a terminal
  • 0 is the file descriptor for STDIN.

So that says

if STDIN is a terminal then ...

Motivation

I'd have to read the whole script to know for sure, but usually it's because the script wants to do something visually slick like clear the screen, or prompt interactively. If you're reading a pipe, there's no point in doing that.

Detail

Okay, let's examine the whole script:

# 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

So this is checking to see if you're on a terminal; if so it looks for an argument with a file name or URL. If it isn't a terminal, then it tries to display the input as html.

Upvotes: 13

Mauro Matsudo
Mauro Matsudo

Reputation: 25

This is very useful to check if a shell script is called by a real user using a terminal or if it was called by a crontab or a daemon (in this case the stdin won't exist).

if [ -t 0 ] --->> if there is a stdin connected (normally a keyboard)

Upvotes: -2

shellter
shellter

Reputation: 37318

From the ksh manual (true for bash too).

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

So file descriptor 0, is std input.

Your code asks, essentially, are we running in a interactive mode, or are we in a batch mode.

I hope this helps.

Upvotes: 2

Related Questions