I have to run a shell script and store whatever is performed in it into a log file. the path can be altered for the log file. how can i do that ?

If you are using bash just execute the file with the -x flag. Consider the following:

$ cat t.sh 
#!/bin/bash


echo "Foo" >&2
echo "Bar" >&1


 $ bash t.sh
Foo
Bar
 $ bash -x t.sh 
+ echo Foo
Foo
+ echo Bar
Bar
 $

You can see that not all context will be saved (i.e. where output is being redirected) but you will see each line of the file as it executes with a + preceding it.

Thanks for your reply.

Actually i've a file called script.sh
I want to log its error and output into /nikita/log/test12.log file, same like other program logs are logged into /var/log/message email log in /var/log/maillog with hostname username and date/time etc.I actually want that what ever is performed in a shell script it should be written in a log file with time stamps. isn't there any script which i can add to the end of my script so that it would generate the logs recursively.

What you are saying is not making much sense. You are first requesting to log the output of your program then you are asking that whatever is performed within that script should also be written to a log. I also dont understand the concept of recursive logging.

In general, logging mechanisms are built-in to the software that uses them not bolted on after the fact. If you want to write a script that does logging, write your own function to do it and use that:

#!/bin/bash

LOG_FILE="the.log"

function logit {
    echo "[${USER}][`date`] - ${*}" >> ${LOG_FILE}
}

logit "This gets written to the log"

However, that does not catch the output of the program like you wish. You could adapt it if you like:

#!/bin/bash

LOG_FILE="the.log"

function logit {
    echo "[${USER}][`date`] - ${*}" >> ${LOG_FILE}
}

while read line; do 
    logit ${line}
    echo ${line}
done

That will simply read all input, log it, then propagate the output to the screen (or other output device).

I simply dont see a way to combine the two into a single utility at the script level.

ok thankz.. i got it now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.