Eugene Belousov
Eugene Belousov

Reputation: 41

Bash: pipe command output to function as the second argument

In my bash script I have a function for appending messages to the log file. It is used as follows:

addLogEntry (debug|info|warning|error) message

It produces nicely formatted lines with severity indication, timestamp and calling function name.

I've been looking for a way to pass output of some standard commands like rm to this function, while still being able to specify severity as the first argument. I'd also like to capture both stdout and stderr.

Is this possible without using a variable? It just feels excessive to involve variables to record a measly log message, and it encumbers the code too.

Upvotes: 4

Views: 3320

Answers (2)

Joshua Rahm
Joshua Rahm

Reputation: 574

You can also use xargs to accomplish this

$ rm -v ... 2>&1 | xargs -I% addLogEntry info %
info removed 'blah1'
info removed 'blah2'
...

In the case of this command, the addLogEntry is called for every line in the input.

Upvotes: 2

Etan Reisner
Etan Reisner

Reputation: 80921

You have two choices:

  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).

Upvotes: 2

Related Questions