显示来自Bash脚本的Unix命令的确切输出 [英] Display exact output of Unix command from a Bash script

查看:49
本文介绍了显示来自Bash脚本的Unix命令的确切输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试打印从传递到bash脚本的命令显示的输出.我要解决的问题是如何使输出看起来完全像从Shell运行命令时的样子.例如,当我运行 ls 时,目录和文件会看到不同的颜色.

I am trying to print out the output displayed from a command passed into a bash script. The problem I am trying to solve is how to get the output to look exactly like it would if you ran the command from the shell. For example, when I run ls, I see different colors for directories vs. files.

以下是到目前为止我的一些示例代码:

Here is some sample code of what I have so far:

#!/bin/bash

command="$@"
output=`$command`
echo "$output"

因此,我的shell脚本接受一个命令,运行该命令,然后输出输出.我知道我可以使用颜色代码和 echo -e 自定义输出的颜色,但是我希望输出看起来像从外壳运行命令时一样.关于如何执行此操作的任何想法吗?

So my shell script takes in a command, runs the command, then prints the output. I know that I can customize the color of the output using color codes and echo -e, but I want the output to look just as it does when I run the command from the shell. Any idea of how I can do this?

推荐答案

如果只需要显示输出,则可以在脚本中内联运行命令(只需让其直接写入stdout,而无需将其输出存储在一些变量).

If all you need is to display the output, you can run the command inline within your script (just let it write to stdout directly, without storing its output in some variable).

也就是说,您可以替换:

That is, you can replace:

output=`$command`
echo $output

具有:

$command

eval $command

如果您还需要将该输出用于某种处理,那将有些棘手.您可以(例如)使用 |tee/var/tmp/some-temp-file.$$ ,然后从临时文件中读取输出.

If you also need that output for some kind of processing, that would be a bit tricky. You can (for instance) use | tee /var/tmp/some-temp-file.$$ and then read the output from the temporary file.

这篇关于显示来自Bash脚本的Unix命令的确切输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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