Create Log File in ksh itself

Hi,

I want to create a log file for a running ksh , and the log file absolute path I want to give in ksh itself.
To elaborate this - Say I have a ksh - timer.ksh and I want to create a log timer_log.log when I run, to trace this. I am aware of the fact that this can be done using redirection parameters. Something like this while executing this script:

ksh timer.ksh 2>&1 timer_log.log

What I want to know if there is possibility that I could put this 'timer_log.log' file path in 'timer.ksh' itself and then I simply have to run

ksh timer.ksh

I might be asking very unpractical question here :confused: .
Could you please advise if this is possible.

Thanks,
Vinay

Yes, you can. The exec builtin can redirect file descriptors for an entire script, just like you'd redirect for external programs.

#!/bin/ksh

# Redirect the current stderr into stdout
exec 2>&1
# Redirect the current stdout into the log file
exec 1>timer_log.log

# Should end up in timer_log.log
echo "This is a message"
# Should also end up in timer_log.log
echo "This is an error message!" >&2
1 Like

Thanks Corona !

I was simply using 2>&1 to redirect previously (was not aware of exec).

I have not tried this solution yet , however I assume after using this nothing will printed on console when I run that script.

Is it also possible to have it redirected in the log file ( for future reference ) as well as have it printed on the console also to get a quick view.

Thanks,
Vinay

You cannot print to one file and get it to appear in two places without using an external program like tee or the like to make one line print twice. So not easily, not cleanly, and the output you get won't necessarily be in the order you expect.

1 Like

One common way is to run the script command before launching the commands you want the output to be both displayed and saved.

eg:

$ script
Script started, file is typescript
$ date
Tue Jun 12 02:04:59 CEST 2012
$ exit
Script done, file is typescript
$ cat typescript
Script started on Tue Jun 12 02:04:57 2012
$ date
Tue Jun 12 02:04:59 CEST 2012
$ exit

Script done on Tue Jun 12 02:05:01 2012
$ 
1 Like