【问题标题】:Detecting the output stream type of a shell script检测 shell 脚本的输出流类型
【发布时间】:2010-10-29 01:11:09
【问题描述】:

我正在编写一个在命令行上使用 ANSI 颜色字符的 shell 脚本。

示例:example.sh

#!/bin/tcsh
printf "\033[31m Success Color is awesome!\033[0m"

我的问题是:

$ ./example.sh > out

$./example.sh | grep 

ASCII 代码将与文本一起原始发送出去,弄乱了输出,通常只会造成混乱。

我很想知道是否有办法检测到这一点,以便我可以针对这种特殊情况禁用颜色。

我已经在 tcsh 手册页和网络上搜索了一段时间,但还没有找到任何特定于 shell 的内容。

我不受 tcsh 的约束,这是我们的团体标准……但谁在乎呢?

是否可以在 shell 脚本中检测您的输出是否被重定向或管道传输?

【问题讨论】:

标签: linux unix shell scripting


【解决方案1】:

据我所知,没有办法确定你的 shell 脚本输出的最终目的地;您唯一能做的就是提供一个允许在输出中抑制控制字符的开关。

【讨论】:

    【解决方案2】:

    在 bourne shell 脚本(sh、bask、ksh、...)中,您可以将标准输出提供给 tty 程序(Unix 中的标准),该程序会告诉您其输入是否为 tty,通过使用-s 标志。

    将以下内容放入“check-tty”:

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

    试试看:

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

    我不使用tcsh,但必须有办法将您的标准输出重定向到tty 的标准输入。如果没有,请使用

        sh -c "tty -s <&1"
    

    作为tcsh 脚本中的测试命令,检查它的退出状态,就完成了。

    【讨论】:

    • sh -c "tty -s
    • 不,不会(我刚刚测试过)。
    【解决方案3】:

    请参阅previous SO question,其中涵盖了 bash。 Tcsh 提供与filetest -t 1 相同的功能,以查看标准输出是否为终端。如果是,则打印颜色内容,否则将其保留。这里是 tcsh:

    #!/bin/tcsh
    if ( -t 1 ) then
            printf "\033[31m Success Color is awesome!\033[0m"
    else
            printf "Plain Text is awesome!"
    endif
    

    【讨论】:

    • csh 不是我的母语。对不起最初的错误
    【解决方案4】:

    输出流类型的检测在问题detect if shell script is running through a pipe中有介绍。

    确定您正在与终端对话后,您可以使用tput 为您正在使用的特定终端检索正确的转义码 - 这将使代码更便携。

    下面给出了一个示例脚本(恐怕在bash 中,因为tcsh 不是我的强项)。

    #!/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}"
    

    有关更多信息,请参阅“man tput”和“man terminfo” - 有各种转义码可供使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-02
      相关资源
      最近更新 更多