检测shell脚本的输出流类型 [英] Detecting the output stream type of a shell script

查看:243
本文介绍了检测shell脚本的输出流类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

示例: example.sh

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

我的问题是在做什么:

$ ./example.sh > out

$./example.sh | grep 

ASCII码将与文本一起原始发送出去,从而破坏了输出,并且通常会引起混乱.

The ASCII codes will be sent out raw along with the text, mucking up the output and just generally causing chaos.

我很想知道是否有一种方法可以检测到这种情况,因此我可以针对这种特殊情况禁用颜色.

I'm interested to know if there is a way to detect this so I could disable color for this special case.

我已经搜索了一段时间tcsh手册页和网络,还没有找到任何特定于shell的东西.

I've search the tcsh man pages and the web for a while and have not been able to find anything shell specific yet.

我不限于tcsh,这是我们的团体标准...但是谁在乎呢?

I'm not bound to tcsh, it's our group standard... but who cares?

是否可以在shell脚本中检测输出是否正在重定向或通过管道传输?

推荐答案

请参阅此

See this previous SO question, which covers bash. Tcsh provides the same functionality with filetest -t 1 to see if standard output is a terminal. If it is, then print the color stuff, else leave it out. Here's tcsh:

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

这篇关于检测shell脚本的输出流类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆