Detecting the output stream type of a shell script

前端 未结 4 1187
隐瞒了意图╮
隐瞒了意图╮ 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:23

    The detection of the output stream type is covered in the question detect if shell script is running through a pipe.

    Having decided that you are talking to terminal, then you can use tput to retrieve the correct escape codes for the particular terminal you are using - this will make the code more portable.

    An example script (in bash I am afraid, as tcsh is not my forte) is given below.

    #!/bin/bash
    
    fg_red=
    fg_green=
    fg_yellow=
    fg_blue=
    fg_magenta=
    fg_cyan=
    fg_white=
    bold=
    reverse=
    attr_end=
    
    if [ -t 1 ]; then
        fg_red=$(tput setaf 1)
        fg_green=$(tput setaf 2)
        fg_yellow=$(tput setaf 3)
        fg_blue=$(tput setaf 4)
        fg_magenta=$(tput setaf 5)
        fg_cyan=$(tput setaf 6)
        fg_white=$(tput setaf 7)
        bold=$(tput bold)
        reverse=$(tput rev)
        underline=$(tput smul)
        attr_end=$(tput sgr0)
    fi
    
    echo "This is ${fg_red}red${attr_end}"
    echo "This is ${fg_green}green${attr_end}"
    echo "This is ${fg_yellow}yellow${attr_end}"
    echo "This is ${fg_blue}blue${attr_end}"
    echo "This is ${fg_magenta}magenta${attr_end}"
    echo "This is ${fg_cyan}cyan${attr_end}"
    echo "This is ${fg_white}white${attr_end}"
    echo "This is ${bold}bold${attr_end}"
    echo "This is ${reverse}reverse${attr_end}"
    echo "This is ${underline}underline${attr_end}"
    

    For more information see "man tput" and "man terminfo" - there are all sorts of escape codes to play with.

提交回复
热议问题