4

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.

2
  • 1
    If you want to pipe the output of a command to addLogEntry, then you'll have to change it to accept the message from STDIN. Then you can do rm file 2>&1 | addLogEntry debug (or something like that). Commented Sep 22, 2015 at 19:34
  • Thanks! I'll try rewriting the function. Commented Sep 22, 2015 at 20:31

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the hint! I may have to resort to the second solution in the end, but I'll try the first one, it keeps the code more readable if nothing else.
I don't know what your function looks like but for the first one you'll just need to detect the number of arguments and then use something like cat or read to read from standard input and do your logging. (If you are using a logging tool it might be able to handle that for you directly in fact. logger can for example.)
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.