Detecting the output stream type of a shell script

前端 未结 4 1189
隐瞒了意图╮
隐瞒了意图╮ 2021-02-07 10:13

I\'m writing a shell script that uses ANSI color characters on the command line.

Example: example.sh

#!/bin/tcsh
printf \"\\033[31m Succ         


        
4条回答
  •  别跟我提以往
    2021-02-07 10:35

    Inside a bourne shell script (sh, bask, ksh, ...), you can feed the standard output to the tty program (standard in Unix) which tells you whether its input is a tty or not, by using the -s flag.

    Put the following into "check-tty":

        #! /bin/sh
        if tty -s <&1; then
          echo "Output is a tty"
        else
          echo "Output is not a tty"
        fi
    

    And try it:

        % ./check-tty
        Output is a tty
        % ./check-tty | cat
        Output is not a tty
    

    I don't use tcsh, but there must be a way to redirect your standard output to tty's standard input. If not, use

        sh -c "tty -s <&1"
    

    as your test command in your tcsh script, check its exit status and you're done.

提交回复
热议问题