tags:

views:

52

answers:

2

I'm writing a bash script that I want by default to output everything into a log file. However, I also want the ability to output it to the calling terminal by request (e.g. parameter) INSTEAD of the log file (so tee is out I believe). Does anyone know of a simple way to do this?

It would be nice if the parameter could be a custom log file OR a reference to a calling terminal.

I'm thinking along the lines of this: (pseudo-code)

#!/bin/bash

if [ ! $1 ]; then
    OUT="default.log"
else
    OUT=$1
fi

#then do this to every call in the script
commands [param] [param] >> ${OUT}

I guess more of what I am asking is, is there an easy way to reference the current terminal for output to? So I could do ./script.sh, ./script.sh custom.log or script.sh TERMINAL?

+2  A: 

Using /dev/stdout as a filename would do what you want.

grddev
Ahh, this is exactly what I was looking for. Been a while since I've done bash scripting. (edit: can't accept the answer for 7 minutes)
tj111
Be advised that `/dev/stdout` is not in the Single UNIX Specification, Version 3. A more portable choice would be `/dev/tty`, which is in the Standard.
Steve Emmerson
+3  A: 

I might go with something like this:

#!/bin/bash

if [[ $1 != --stdout ]]; then
    exec >> "${1:-default.log}"
fi

commands [param] [param]

Result: If the user passes --stdout then output goes to stdout, otherwise it goes to a log file. The user can pass the log file name on the command-line, and if they don't specify one it defaults to default.log.

The exec part is nice because it redirects all future output from your script. It saves you from having to add >> ${OUT} to every single command.

John Kugelman
Oh wow thanks for this. So many neat little things in bash that are great to use but hard to find.
tj111
This is much nicer, but would you not need to add `--stdout` to the arguments on the exec line?
grddev
@grddev: No that's just an argument to the script. By not redirecting the output it will go to `stdout` if the script is passed `--stdout`. If it's not then the `exec` will send it to a named file or to `default.log` if a name is not supplied.
Dennis Williamson
@Dennis: Ah, I wasn't aware that `exec` doesn't actually do (the C function) `exec` when you do not supply any arguments, but instead just redirects the inputs/outputs of the running instance.
grddev