Masroor
Masroor

Reputation: 908

Running a few commands from bash script

I thought that this should be straightforward, but the result is puzzling me.

When I run a bash script using the command,

sudo ./restartccpd.bash

nothing appears on the screen. Also issue of

sudo /etc/init.d/ccpd status

independently from screen after running the script produces empty, rather than showing the pid's of the daemon. This evidences that only the pkill command is working.

The contents of the script is,

#!/bin/bash

sudo pkill -9 ccpd
sudo /etc/init.d/ccpd start
sudo /etc/init.d/ccpd status

The commands work fine when run from a terminal. But when run as a script, as pointed out above, it is not working as expected.

I tried inserting sleep command between commands, without any avail. Also, nothing appears in syslog. So, I can not diagnose the problem.

Any suggestion will be appreciated.

Upvotes: 2

Views: 1999

Answers (2)

As larsks correctly diagnosed, pkill ccpd kills all processes whose name contains ccpd. Including your script.

The immediate fix is to pass the -x option to pkill, so that it only matches processes whose name is exactly ccpd.

Note that if your script contains sudo commands, it doesn't need to be invoked with sudo. Alternatively, you can remove all the sudo calls from your script, and call it with sudo.

You should not run this script, however. You should normally call the init script to shut down a service: /etc/init.d/ccpd stop. In addition to killing the daemon, this may perform other necessary clean up such as removing temporary files and locks. The only case when you should use kill -9 is if something goes seriously wrong, causing /etc/init.d/ccpd stop to fail, and in that case you should do the necessary clean up manually before restarting the daemon.

The proper way to do what you're trying to do is

sudo /etc/init.d/ccpd restart

(assuming your distribution uses the traditional SysVinit — if it uses upstart, you should run sudo service ccpd restart instead).

Upvotes: 0

larsks
larsks

Reputation: 311298

pkill will kill anything contained ccpd in the command name. Your script is called restartccpd.bash. The very first line is:

pkill ccpd

So the script starts, runs pkill (which produces no output) and promptly kills itself. Ta da!

The easiest solution is to rename the script. You could also do something like:

kill $(pgrep -l ccpd | grep -v restartccpd | awk '{print $1}')

This produces a list of proccess names and pids matching ccpd, then removes restartccpd from the list, and then kills the processes with kill.

Upvotes: 6

Related Questions