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