LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   Need help with Bash Script (https://www.linuxquestions.org/questions/linux-software-2/need-help-with-bash-script-939683/)

seway 04-13-2012 02:29 PM

Need help with Bash Script
 
Hello guys im trying to make a bash script that will run a program and sleep for 15 seconds running the program and it will stop the program and sleep 300 seconds and than start the program again, here the code i have but its not working:

Quote:

#!/bin/bash

PID=""

function get_pid {
PID=`ps ax |grep ata_pep |cut -d " " -f 1`
}

function start {
get_pid
if [ -z $PID ]; then
echo "Starting Ata Pep.."
nice -n -20 /prog/ata_pep xxx.xxx.xxx.xxx &
get_pid
echo "Done. PID=$PID"
sleep 15
kill $PID
sleep 300
start
fi
}
And im running the script using: ./nameofthescript start

I hope someone can help me with this issue.

Thanks a lot for all the attention.

Ser Olmy 04-13-2012 03:02 PM

You could use $!:

#!/bin/bash

Code:

echo "Starting Ata Pep.."
while [ 1 ] ; do
  nice -n -20 /prog/ata_pep xxx.xxx.xxx.xxx &
  PID=$!
  echo "Done. PID=$PID"
  sleep 15
  kill $PID
  sleep 300
done


MensaWater 04-13-2012 03:04 PM

You have the function named "start" but then you call "start" from within the function definition. It would need to be called AFTER the function definition. That is to say functions don't get executed when defined but rather when called later in the script. (e.g. calling get_pid in your start function is valid because you previously defined get_pid.)

seway 04-13-2012 03:06 PM

Thanks a lot guys i found out the problem and now its working perfect.

This topic can be post as solved.

rknichols 04-13-2012 03:12 PM

Well as written, the script sets variable PID to null, defines a function "get_pid", defines a function "start", and then exits without ever calling either function. The parameter that you passed when invoking the script is never used.

Once you correct that by inserting a call to "start" (perhaps with a test of the supplied parameter, "$1") following the function definitions, you will find that the script will run for quite a while but will eventually run out of memory due to the infinite recursion of the "start" function calling itself. Rather than doing that, you should just write the body of the "start" function as an infinite loop
Code:

while :; do
    ...
done

Also, if your installation includes the pgrep command, the function "get_pid" could be deleted and the call replaced by
Code:

PID=`pgrep -x ata_pep`
See the manpage for pgrep for details. (I'll leave the possibility of more that one "ata_pep" process running simultaneously as an exercise, but you might want to look at the "-P ppid" option of the pgrep command.)


All times are GMT -5. The time now is 03:46 PM.