将Bash命令的输出作为第二个参数传递给函数

4
在我的bash脚本中,我有一个用于将消息添加到日志文件的函数。它的使用方法如下:
addLogEntry (debug|info|warning|error) message

它可以生成格式良好的行,其中包含严重性指示、时间戳和调用函数名称。

我一直在寻找一种方法,可以将一些标准命令(如rm)的输出传递给此函数,同时仍然能够指定严重性作为第一个参数。我还想捕获标准输出和标准错误。

是否可以不使用变量就实现这个功能呢?涉及使用变量记录单个日志消息似乎过于冗余,也会使代码变得繁琐。


1
如果你想将命令的输出导入到 addLogEntry 中,那么你需要更改它的设置以接受来自 STDIN 的 message。之后,你可以执行 rm file 2>&1 | addLogEntry debug(或者类似的操作)。 - gen_Eric
谢谢!我会尝试重写这个函数。 - Eugene Belousov
2个回答

2

你有两个选择:

  1. You can add support to your addLogEntry function to have it accept the message from standard input (when no message argument is given or when - is given as the message).

  2. You can use Command Substitution to run the command and capture its output as an argument to your function:

    addLogEntry info "$(rm -v .... 2>&1)"
    

    Note that this will lose any trailing newlines in the output however (in case that matters).


谢谢你的提示!最终我可能不得不采用第二种解决方案,但我会先尝试第一种,如果没有其他问题,它可以使代码更易读。 - Eugene Belousov
我不知道你的函数长什么样子,但对于第一个函数,你只需要检测参数的数量,然后使用类似于catread的东西从标准输入读取并记录日志。 (如果你正在使用日志工具,它实际上可能能够直接为你处理。例如,logger就可以。) - Etan Reisner

2
您可以使用xargs来完成此操作。
$ rm -v ... 2>&1 | xargs -I% addLogEntry info %
info removed 'blah1'
info removed 'blah2'
...

在这个命令的情况下,addLogEntry将被用于输入中的每一行。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接