check isatty in bash

后端 未结 4 520
予麋鹿
予麋鹿 2020-12-16 12:29

I want my shell to detect if human behavior, then show the prompt.

So, assume the file name is test.bash

#!/bin/bash
if [ \"x\" != \"${PS1:-x}\" ] ;t         


        
相关标签:
4条回答
  • 2020-12-16 13:03

    You could make use of the /usr/bin/tty program:

    if tty -s
    then
        # ...
    fi
    

    I admit that I'm not sure how portable it is, but it's at least part of GNU coreutils.

    0 讨论(0)
  • 2020-12-16 13:18

    From help test:

     -t FD          True if FD is opened on a terminal.
    
    0 讨论(0)
  • 2020-12-16 13:21

    Note that in bash scripts (see the test expr entry in man bash), it is not necessary to use the beefy && and || shell operators to combine two separate runs of the [ command, because the [ command has its own built-in and -a and or -o operators that let you compose several simpler tests into a single outcome.

    So, here is how you can implement the test that you asked for — where you flip into batch mode if either the input or the output has been redirected away from the TTY — using a single invocation of [:

    if [ -t 0 -a -t 1 ]
    then
        echo Interactive mode
    else
        echo Batch mode
    fi
    
    0 讨论(0)
  • 2020-12-16 13:22

    to elaborate, I would try

     if [ -t 0 ] ; then
        # this shell has a std-input, so we're not in batch mode 
       .....
     else
        # we're in batch mode
    
        ....
     fi
    

    I hope this helps.

    0 讨论(0)
提交回复
热议问题