2

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:

  • User runs script. (script logs stdout/stderr from now on to a logfile)
  • User does other stuff/runs other commands/echoes/etc and all of these are logged in logfile.

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.

Dororo
  • 3,420
  • 2
  • 30
  • 46

4 Answers4

5

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.

Ben Jackson
  • 90,079
  • 9
  • 98
  • 150
1

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

csd
  • 934
  • 5
  • 12
0

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] ...
0

How about an alias?

alias Start-Script='script logfile.txt'
SuperJames
  • 767
  • 4
  • 14