Redirections from script himself
You could plan redirections from the script itself:
#!/bin/bash
exec 1>>logfile.txt
exec 2>&1
/bin/ls -ld /tmp /tnt
Running this will create/append logfile.txt
, containing:
/bin/ls: cannot access '/tnt': No such file or directory
drwxrwxrwt 2 root root 4096 Apr 5 11:20 /tmp
Log to many different files
You could create two different logfiles, appending to one overall log and recreating another last log:
#!/bin/bash
if [ -e last.log ] ;then
mv -f last.log last.old
fi
exec 1> >(tee -a overall.log /dev/tty >last.log)
exec 2>&1
ls -ld /tnt /tmp
Running this script will
- if
last.log
already exist, rename them to last.old
(overwriting last.old
if they exist).
- create a new
last.log
.
- append everything to
overall.log
- output everything to the terminal.
Simple and combined logs
#!/bin/bash
[ -e last.err ] && mv -f last.err lasterr.old
[ -e last.log ] && mv -f last.log lastlog.old
exec 2> >(tee -a overall.err combined.log /dev/tty >last.err)
exec 1> >(tee -a overall.log combined.log /dev/tty >last.log)
ls -ld /tnt /tmp
So you have
last.log
last run log file
last.err
last run error file
lastlog.old
previous run log file
lasterr.old
previous run error file
overall.log
appended overall log file
overall.err
appended overall error file
combined.log
appended overall error and log combined file.
- still output to the terminal
And for interactive session, use stdbuf
:
If you plan to use this in interactive shell, you must tell tee
to not buffering his input/output:
# Source this to multi-log your session
[ -e last.err ] && mv -f last.err lasterr.old
[ -e last.log ] && mv -f last.log lastlog.old
exec 2> >(exec stdbuf -i0 -o0 tee -a overall.err combined.log /dev/tty >last.err)
exec 1> >(exec stdbuf -i0 -o0 tee -a overall.log combined.log /dev/tty >last.log)
Once sourced this, you could try:
ls -ld /tnt /tmp