Searching for logging technic's while running bash command/scripts we ran across these to elegant ways to ensure all logging is captured when running a script.
Quick and dirty : (Credit to christian)
to get the ssh output to your logfile, you have to redirect
stderr to stdout. you can do this by appending 2>&1 after your bash script.
it should look like this:
#!/bin/bash
(
...
) 2>&1 | tee ...
when this does not display the mesages in the right order, try to add another subshell:
#!/bin/bash
((
...
) 2>&1) | tee ...
Super Nice: (Credit to post by: nicerobot )
I generally put something similar to the following at the beginning of every script (especially if it'll run as a daemon):
#!/bin/bash
exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>log.out 2>&1
# Everything below will go to the file 'log.out':
Explanation:
exec 3>&1 4>&2Saves file descriptors so they can be restored to whatever they were before redirection or used themselves to output to whatever they were before the following redirect.trap 'exec 2>&4 1>&3' 0 1 2 3Restore file descriptors for particular signals. Not generally necessary since they should be restored when the sub-shell exits.exec 1>log.out 2>&1Redirectstdoutto filelog.outthen redirectstderrtostdout. Note that the order is important when you want them going to the same file.stdoutmust be redirected beforestderris redirected tostdout.
From then on, to see output on the console (maybe), you can simply redirect to
&3. For example,echo "$(date) : part 1 - start" >&3
will go to wherever
stdout was directed, presumably the console, prior to executing line 3 above.