Bri*_*aro 14 unix linux shell scripting
我正在编写一个在命令行上使用ANSI颜色字符的shell脚本.
示例:example.sh
#!/bin/tcsh
printf "\033[31m Success Color is awesome!\033[0m"
Run Code Online (Sandbox Code Playgroud)
我的问题在于:
$ ./example.sh > out
Run Code Online (Sandbox Code Playgroud)
要么
$./example.sh | grep
Run Code Online (Sandbox Code Playgroud)
ASCII码将与文本一起原始发送,使输出混乱并且通常导致混乱.
我很想知道是否有办法检测到这一点,所以我可以禁用这种特殊情况的颜色.
我已经在tcsh手册页和网页上搜索了一段时间,但还没有找到任何特定于shell的内容.
我不一定要tcsh,这是我们的团队标准......但是谁在乎呢?
是否可以在shell脚本中检测输出是否被重定向或管道传输?
dwc*_*dwc 13
请参阅此前的SO问题,其中包含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
Run Code Online (Sandbox Code Playgroud)
在一个bourne shell脚本(sh,bask,ksh,...)中,你可以tty通过使用-s标志将标准输出提供给程序(Unix中的标准),该程序告诉你输入是否为tty .
将以下内容放入"check-tty":
#! /bin/sh
if tty -s <&1; then
echo "Output is a tty"
else
echo "Output is not a tty"
fi
Run Code Online (Sandbox Code Playgroud)
试试吧:
% ./check-tty
Output is a tty
% ./check-tty | cat
Output is not a tty
Run Code Online (Sandbox Code Playgroud)
我不使用tcsh,但必须有一种方法将标准输出重定向到tty标准输入.如果没有,请使用
sh -c "tty -s <&1"
Run Code Online (Sandbox Code Playgroud)
作为tcsh脚本中的测试命令,检查其退出状态,您就完成了.
| 归档时间: |
|
| 查看次数: |
4926 次 |
| 最近记录: |