Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to stdout in bash

Tags:

bash

Is there a filename that is assignable to a variable (i.e. not a magic builtin shell token like &1) that will let me redirect to stdout?

What I finally want to do is run something like this in a cron script:

LOG=/tmp/some_file
...
some_command 2>&1 >> $LOG
echo "blah" >> $LOG
...

Conveniently, this lets me turn off log noise by redirecting to /dev/null later when I'm sure there is nothing that can fail (or, at least, nothing that I care about!) without rewriting the whole script. Yes, turning off logging isn't precisely best practice -- but once this script works, there is not much that can conceivably go wrong, and trashing the disk with megabytes of log info that nobody wants to read isn't desired.
In case something unexpectedly fails 5 years later, it is still possible to turn on logging again by flipping a switch.

On the other hand, while writing and debugging the script, which involves calling it manually from the shell, it would be extremely nice if it could just dump the output to the console. That way I wouldn't need to tail the logfile manually.

In other words, what I'm looking for is something like /proc/self/fd/0 in bash-talk that I can assign to LOG. As it happens, /proc/self/fd/0 works just fine on my Linux box, but I wonder if there isn't such a thing built into bash already (which would generally be preferrable).

like image 734
Damon Avatar asked Dec 20 '22 02:12

Damon


1 Answers

Basic solution:

#!/bin/bash
LOG=/dev/null

# uncomment next line for debugging (logging)
# LOG=/tmp/some_file

{
  some_command
  echo "blah"
} | tee 1>$LOG 2>&1

More evolved:

#!/bin/bash

ENABLE_LOG=0       # 1 to log standard & error outputs
LOG=/tmp/some_file

{
  some_command
  echo "blah"
} | if (( $ENABLE_LOG ))
then
  tee 1>$LOG 2>&1
fi

More elegant solution from DevSolar's idea:

#!/bin/bash

# uncomment next line for debugging (logging)
# exec 1> >(tee /tmp/some_file)  2>&1

some_command
echo "blah"
like image 180
oHo Avatar answered Jan 08 '23 02:01

oHo