2

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Probably echo $$ > ${0}.pid -> echo $$ > /suitable/path/$(basename $0).pid would be useful. But depends on user's convenience.
So how do I schedule my script, would it be as: nohup myScript.sh > /script.log & can you please explain in steps.
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.
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 &.
You are mixing the two proposed solutions. With ...> out.txt you don't need exec....
1

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 :

#!/bin/bash
echo $$ > myScript.pid
while :; do echo "Hello"; sleep 1; done

2 Comments

I did not get, can you please elaborate. with steps that I need to do
Those are the steps, now in consecutive order.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.