Write to the terminal after redirecting stdout to a file without using stderr?

I have two shell scripts, one of which serves as the main "program", and the other as a "library".

In a few places in the "program" I will do something like: log "$thing" >> "$logfile" , where log is the function defined in the "library".

 # program.sh logfile="log.txt" stuff="hahah heheh hoho" . library.sh for thing in $stuff; do log "$thing" >> "$logfile" done 

My question is: is there a way to redirect part of the output from a function back to the terminal without using stderr ?

 # library.sh log () { # This gets written to the log echo "`date --rfc-3339=seconds`: $1" # How to write this to the terminal *without* using stderr? echo "Info: Message written to log." >&2 } 

I want to avoid using stderr because in my real program it is possible to redirect errors to a file, but the messages that I want to send to the terminal are informational and not errors and should always be displayed on the terminal.

+7
source share
2 answers

Open /dev/tty on another FD.

 exec 0< /dev/null exec 1> /dev/null exec 2> /dev/null exec 3> /dev/tty echo 'Hello, World!' >&3 
+12
source

You can write directly to /dev/tty every time you want to write to the terminal:

 echo "hello world" > /dev/tty 

For a small example:

 $ cat writer.sh #!/bin/sh echo "standard output" echo "standard error" >&2 echo "direct to terminal" > /dev/tty $ ./writer.sh > /tmp/out 2> /tmp/err direct to terminal $ cat /tmp/out standard output $ cat /tmp/err standard error $ 
+8
source

All Articles