Reputation: 3440
I've read how to log certain scripts or commands individually, but nothing on how to log all commands from within a BASH shell. What I want to do is:
A less wordy / more codey example:
exec > >(tee logfile.log) when typed in by the user does exactly what I want to do. It logs stdout to logfile.log and will continue to do so until the bash shell is closed. However, running this very command as a script does not do this. I want it to.
Upvotes: 2
Views: 2191
Reputation:
Just for reference, if someone wants to do this to start a daemon (background process), i'd suggest to look at the excellent daemonize.
daemonize
allows you to start a process from a certain directory (without cd'ing), redirecting stdout, redirecting stderr, writing a pidfile or lockfile, and run as a certain user. This is very useful eg. when writing your own small init script.
synopsis from the man page tells you most about its quite straightforward usage:
daemonize [-a] [-c directory] [-e stderr] [-o stdout] [-p pidfile] [-l lockfile] [-u user] [-v] path [arg] ...
Upvotes: 0
Reputation: 944
$ bash | tee /tmp/logs/logfile.txt
$ ls /tmp/logs
logfile.txt
$ < CTRL-D>
exit
$ cat /tmp/logs/logfile.txt
logfile.txt
if you're looking for just stdout then this seems to work. If you want stdin/stdout then script is the way to go as mentioned previously.
Upvotes: 1
Reputation: 93890
You can't do this in a script that runs under its own shell (i.e. it starts with #!/bin/bash
and you chmod +x
and invoke it like an executable). The redirect affects the subshell but it can't reach the parent to do what you want. You can .
the file (as in . ./myscript.sh
) which will execute the commands in your shell and then you can redirect things as you want.
The other way to do it would be for your script to start a subshell itself (which would inherit stdin, stdout, stderr). This is what the script
command does. It logs everything to a file named (by default) typescript
until the user exits the subshell.
Upvotes: 5