Dark Matter
Dark Matter

Reputation: 2311

Setting Up log for a bash script

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

Upvotes: 2

Views: 214

Answers (2)

svante
svante

Reputation: 1385

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

Upvotes: 1

jbr
jbr

Reputation: 6258

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.

Upvotes: 1

Related Questions