Enable logging from within the shell script

Bash on Oracle Linux 6.3

I have a shell script whose output I want to redict to a log file. So, I can simply redirect the output as shown below.

# cat myscript.sh
#### I actually want some logging mechanism here which will redirect the output to a log file
echo 'hello world'

# ./myscript.sh > /tmp/mylog.txt
#
# cat /tmp/mylog.txt
hello world

But, this script is not going to be executed manually or through cron job. Instead, it is invoked by Symantec Netbackup program remotely.
So, I don't get a chance to redirect the output to a log file as shown above.
So, I need to have some mechanism within the script itself to redirect the output to a file. Any idea how I can do this ?

These two lines in your script will redirect stdout and stderr to a file.

exec >logfile
exec 2>&1
1 Like

THANK YOU.. THANK YOU...
YOU ARE AN ANGEL Corona. God Bless.

How does this work ? Man page of exec (some Bash Bulletin thing) wasn't very helpful to me.

The netbackup way is to litter the shell script with lot of echo >> as shown below.

RMAN_LOG_FILE=/usr/openv/netbackup/logs/rman/rman_DB_backup_weekly_${CUR_DATE}.out


if [ -f "$RMAN_LOG_FILE" ]
then
        rm -f "$RMAN_LOG_FILE"
fi


echo >> $RMAN_LOG_FILE
chmod 666 $RMAN_LOG_FILE


echo Script $0 >> $RMAN_LOG_FILE
echo ==== started on `date` ==== >> $RMAN_LOG_FILE
echo >> $RMAN_LOG_FILE
ORACLE_SID=BMIBPRD1
export ORACLE_SID


ORACLE_USER=oracle


TARGET_CONNECT_STR=/


RMAN=$ORACLE_HOME/bin/rman
echo >> $RMAN_LOG_FILE
echo   "RMAN: $RMAN" >> $RMAN_LOG_FILE
echo   "ORACLE_SID: $ORACLE_SID" >> $RMAN_LOG_FILE
echo   "ORACLE_USER: $ORACLE_USER" >> $RMAN_LOG_FILE
echo   "ORACLE_HOME: $ORACLE_HOME" >> $RMAN_LOG_FILE
1 Like

exec seems to do a lot of different things, but at core, all it means is "do (this) to the current process" -- instead of what a shell is usually used for, "do (this) to (that) new process".

So this is plain ordinary shell redirection, applied to the shell itself. In effect this allows it to open and close files. (Closing is a special syntax, like exec 2>&- ) Files are referred to by arbitrary numbers. 0 is standard input, 1 is standard output, and 2 is standard error.

You could also run a command like exec commandname . Since this applies to the shell itself, the shell would be replaced by that command, and when it finished you'd have no more shell. This is what always happens, technically, but the shell normally makes a copy of itself first.

1 Like