Take the 2-minute tour ×

I have a bash script which I want it to run as a daemon as it checks for a condition does some work and sleeps for some time and the cycle repeats.

I demonize the script as : nohup myScript.sh &

How can I setup the logging for the same script as it has same echo commands which prints some statements and how to make sure I have the pid of the script if I want to kill it later.

Can anyone suggest how I can achieve the same

share|improve this question

2 Answers 2

up vote 1 down vote accepted

If you look at the I/O redirection chapter in the Advanced Bash-Scripting Guide, then you see that you can redirect all output to a file by doing something like, in the top of your script:

exec 2>&1
exec 1>>out.log 

The first line redirects stderr to stdout, and the second line appends stdout to out.log. If you do this, then you can use echo to write specific messages to the log-file, and the output of all commands, which you haven't silenced will be written to the log-file as well.

Bash has a lot of special variables, you can get an overview of these in the Special Shell Variables reference card. One of these is $$, which hold the scripts PID. To save this, you can do the following:

echo $$ > ${0}.pid

This will create a file name <file name of script>.pid, containing the PID of the script.

share|improve this answer
Probably echo $$ > ${0}.pid -> echo $$ > /suitable/path/$(basename $0).pid would be useful. But depends on user's convenience. –  anishsane Oct 7 '13 at 10:44
So how do I schedule my script, would it be as: nohup myScript.sh > /script.log & can you please explain in steps. –  Dark Matter Oct 7 '13 at 11:00
Thanks got it working fine. –  Dark Matter Oct 7 '13 at 11:26
Where can I use the exec 2>&1 and exec 1>>out.log. What I have done is I have looged the pid as soon as I enter the script and I have scheduled the script as nohup myscript.sh >> out.txt &. Now where can I use the stderr and stdout statements which you mentioned initially. –  Dark Matter Oct 7 '13 at 11:56
The exec 2>&1; exec 1>>out.log has to go in the top of myScript.sh, and then you can just execute the script with nohup myScript.sh &. –  jbr Oct 7 '13 at 12:12

Put the following line in the beginning of your script. It saves the pid for later :

echo $$ > myScript.pid

Start your script capturing output for logging (from the nohup man page example) :

nohup myScript.sh > myScript.log &

Kill the script later by :

kill -9 `cat myScript.pid`

Simple myScript.sh example :

echo $$ > myScript.pid
while :; do echo "Hello"; sleep 1; done
share|improve this answer
I did not get, can you please elaborate. with steps that I need to do –  Dark Matter Oct 7 '13 at 11:01
Those are the steps, now in consecutive order. –  svante Oct 7 '13 at 11:46
Thanks got it working fine. –  Dark Matter Oct 7 '13 at 11:53

Your Answer


