Reputation: 4755
I am trying to write a shell script that looks if a particular program is running and if it is not, it restarts the service. Also it checks if the interface is in promiscuous mode. If it is not, it puts it in that mode.
To check if prog xyz
is running, I can do the following on commandline
ps -ef | grep -v grep | grep xyz | wc -l
If it returns 0, progrma is not running, else it is running
Similarly to check if the interface is in promisc mode I can do the following on the command line
ip link show eth0 | grep -i promisc | wc -l
Again if return is 1, interface is in promisc mode.
The problem comes when I try to bundle it all in a shell script.
#!/bin/bash
SERVICE="daemonlogger"
x=$(ps -ef|grep -v grep|grep $SERVICE|wc -l)
if [ "$x" -eq 1 ]; then
run=0
else
run=1
fi
IF_NAME="eth0"
y=$(ip link show $IF_NAME|grep -i promisc|wc -l)
if [ "$y" -eq 1 ]; then
:
else
ifconfig $IF_NAME promisc up
fi
if [ "$run" -eq 1 ]; then
service $SERVICE restart > /dev/NULL 2>&1
fi
echo $run
The output of commands if run from the command line is
[root@dheerajpc Desktop]# ps -ef | grep -v grep | grep daemonlogger | wc -l
0
[root@dheerajpc Desktop]# ip link show eth0 | grep -i promisc | wc -l
0
Here's the output of running it in debug mode
[root@dheerajpc Desktop]# bash -x check_daemonlogger
+ SERVICE=daemonlogger
++ ps -ef
++ wc -l
++ grep daemonlogger
++ grep -v grep
+ x=2
+ '[' 2 -eq 1 ']'
+ run=1
+ IF_NAME=eth0
++ grep -i promisc
++ ip link show eth0
++ wc -l
+ y=0
+ '[' 0 -eq 1 ']'
+ ifconfig eth0 promisc up
+ '[' 1 -eq 1 ']'
+ service daemonlogger restart
+ echo 1
1
As can be seen the output of first command is not what is expected, while the output of second command is correct.
What am I doing wrong here?
Upvotes: 0
Views: 4403
Reputation: 72755
Not exactly an answer but a bunch of comments.
You should consider using a pidfile
rather than relying on ps, grep, wc etc. to track the process. Write the pid to a file and use that to check if the process is running. You've already hit errors with your current approach.
Why do you want to check the status of the interface? Can't you just switch it into promiscuous mode anyway? I haven't played with this but this is the first thing that occurred to me.
Upvotes: 1