You are not logged in.

#1 2013-10-05 08:32:03

satori
Member
Registered: 2013-01-21
Posts: 29

Bash function - command wrapper with logging needed

Hello!

I'm preparing automation scripts and I need a function which could:
1. Execute a bash command and return its exit status
2. Show both stdout and stderr on screen
3. Append both stdout and stderr to a single log file, preserving order

So far I have:

execCmd()
{
(eval "$@" 2>&1) | tee -a $LOG_FILE
return ${PIPESTATUS[0]}
}

Unfortunately, when I'm using it with pacman to install some package, it doesn't capture all of output e.g. progress bars are not visible nor logged.

I also tried using 'script' command but it had its own drawbacks.

Do you have any suggestions how to improve it?
Do you have your own similar logging wrappers?

Offline

#2 2013-10-20 15:29:12

cmtptr
Member
Registered: 2008-09-01
Posts: 135

Re: Bash function - command wrapper with logging needed

Pacman (or whatever underlying utility it uses) probably chooses not to draw progress bars when it detects that its stdout isn't a tty.  The only way I know of to do this is to create a pseudotty and execute your commands with that as their stdout, then read from the pty and redirect to the real stdout (and handle whatever logging functions you want).

Notice, though, that the reasons apps like pacman are smart about what they write to stdout when it's not a tty is because things like progress bars involve a lot of escape codes to reposition the cursor and redraw character positions on the terminal.  If you write that kind of stuff to a file, it makes for a very ugly and difficult to read log.  So you may want to reconsider exactly what you're trying to accomplish here.

Offline

#3 2013-10-30 21:07:40

satori
Member
Registered: 2013-01-21
Posts: 29

Re: Bash function - command wrapper with logging needed

Thank you for your reply, cmtptr, it explained a lot.
I thought I might be using redirections in a wrong way but it looks like you described, that pacman internally produces different output when it is not connected to tty.
It's good to know that pty might be a solution but I want to keep my scripts simple. For that reason, I'll stay with limited output, it should be enough for my purpose.

Offline

Board footer

Powered by FluxBB