ado
ado

Reputation: 1471

Testing if a Daemon is alive or not with Shell

I have a log_sender.pl perl script that when executed runs a daemon. I want to make a test, using Shell:

 #!/bin/bash                                                                                                                              

 function log_sender()
 {
     perl -I $HOME/script/log_sender.pl
 }

 (
   [[ "${BASH_SOURCE[0]}" == "${0}" ]] || exit 0
   function check_log_sender()
      {
          if [ "ps -aef | grep -v grep log_sender.pl" ]; then
              echo "PASSED"
              else
              echo FAILED
          fi
     }


     log_sender
     check_log_sender

 )

Unfortunately when I run this my terminal becomes:

 -bash-4.1$ sh log_sender.sh 
 ...   
 ...

What am I doing wrong?

Upvotes: 0

Views: 158

Answers (1)

tripleee
tripleee

Reputation: 189937

> if [ "ps -aef | grep -v grep log_sender.pl" ]; then

This is certainly not what you want. Try this:

if ps -aef | grep -q 'log_sender\.pl'; then
    ...

In a shell script, the if construct takes as its argument a command whose exit status it examines. In your code, the command is [ (also known as test) and you run it on the literal string "ps -aef | grep -v grep log_sender.pl" which is simply always true.

You probably intended to check whether ps -aef outputs a line which contains log_sender.pl but does not contain grep; that would be something like ps -aef | grep -v grep | grep 'log_sender\.pl' but you can avoid the extra grep -v by specifying a regular expression which does not match itself.

The -q option to grep suppresses any output; the exit code indicates whether or not the input matched the regular expression.

The perl invocation is also not correct; the -I option requires an argument, so you are saying effectively just perl and your Perl interpreter is now waiting for you to type in a Perl script for it to execute. Apparently the script is log_sender.pl so you should simply drop the -I (or add an argument to it, if you really do need to add some Perl library paths in order for the script to work).

Finally, if you write a Bash script, you should execute it with Bash.

chmod +x log_sender.sh
./log_sender.sh

or alternatively

bash ./log_sender.sh

The BASH_SOURCE construct you use is a Bashism, so your script will simply not work correctly under sh.

Finally, the parentheses around the main logic are completely redundant. They will cause the script to run these commands in a separate subshell for no apparent benefit.

Upvotes: 1

Related Questions