Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: pipe command output to function as the second argument

Tags:

linux

bash

shell

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.

like image 441
Eugene Belousov Avatar asked Oct 13 '25 10:10

Eugene Belousov


2 Answers

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

like image 74
Etan Reisner Avatar answered Oct 14 '25 23:10

Etan Reisner


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.

like image 20
Joshua Rahm Avatar answered Oct 15 '25 00:10

Joshua Rahm