Bash:特技程序进入思考stdout是一个交互式终端

我想通过管道运行程序的输出,但是当它检测到stdout不是交互式 shell时,它显然表现不同.

如何在正常情况下通过管道欺骗它?

我假设程序将调用glibc函数isatty()来检查stdout是否是终端.对于在终端上使用彩色输出或ANSI终端的其他功能(如光标定位或线擦除/重绘)的程序而言,这是很常见的.

您可以使用LD_PRELOAD环境变量欺骗程序. LD_PRELOAD由ELF链接器处理,并告知应在所有其他链接之前加载动态库.使用此功能可以覆盖库函数,在您的情况下glibc函数isatty().例如,您可以按照此article.

我为你准备了一个例子:

首先创建文件libisatty.c:

/**
 * Overrides the glibc function. Will always return true.
 *
 * Note: Although this should be ok for most applications it can
 * lead to unwanted side effects. It depends on the question
 * why the programm calls isatty()
 */
int isatty(int param) {
    return 1;
}

并将其编译为共享库:

gcc -shared -o libisatty.so  libisatty.c

它应该建立良好.

现在是时候测试库了. :)我已经使用命令ls –color = auto进行测试. ls调用isatty()来决定它是否应该为它的输出着色.如果输出重定向文件或管道,则不会着色.您可以使用以下命令轻松测试:

ls --color=auto        # should give you colorized output
ls --color=auto | cat  # will give you monochrome output

现在我们将使用LD_PRELOAD环境var再次尝试第二个命令:

LD_PRELOAD=./libisatty.so ls --color=auto | cat

你应该看到彩色输出.

btw cool usename:uʍopǝpısdn!!:D

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...