简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM