0

Is the following script right??? It was doing OK until yesterday!

I've written the following script to help a cron job running every minute and calling some other script which may cause a command to be executed more than once, the expected behaviour is to have 4 process of the job, anything less or more should be causing a restart, so please let me know if the following script is right or not?

#! /bin/bash

case "$(pidof command | wc -w)" in

0)  echo "Restarting command:     $(date)" >> log

    /usr/bin/sh x.sh
    ;;

4)  # all ok

    echo "All OK" >> log
    ;;

*)  for pid in $(ps -ef | grep "x" | grep "y" | awk '{print $2}'); do kill -9 $pid; done

    echo "Removed PIDs and RESTARTING FFMPEG: $(date)" >> /root/afarinEidSTs/log

    /usr/bin/sh x.sh
    ;;

esac

It will not kill proccesses even if they get more than 4, why?

In log file, I will just see the result of "Restarting command: $(date)".

It is so weird, because pidof ffmpeg | wc -w will display 23, but the script is not killing all and restarting them again!


I have also tried using ([0-3]) instead of 0) as @jordanm said, but didn't help.

6
  • Uh, so you intend to kill all processes on your system which contain both the letters "x" and "y"? This will never allow it get up to 4, so it will only work if you have exactly 4 the first time you run it. The first condition should probably be [0-3]. – jordanm Apr 3 '17 at 6:18
  • @jordanm Did what you said, but it got more again! BTW, won't [0-3] be the same as *) including 1-2-3 since not mentioned in first conditions? – Parsa Samet Apr 3 '17 at 6:20
  • If you're literally running pidof command, when the command you're actually running is /usr/bin/sh x.sh.... won't the number of PIDs be always 0? – muru Apr 3 '17 at 7:25
  • No, x.sh is calling command inside itself, so pidof command will show the number of command not x.sh. – Parsa Samet Apr 3 '17 at 7:27
  • Is the command a script or a linux built in or a c/java binary? – ss_iwe Apr 3 '17 at 7:30
1

It's probably because your cron or something that you are using for doing your jobs, cannot execute all commands you have used. To fix the issue, I recommend you use the the bsolute path of any command - taken by using which pidof, which grep &c :

#!/bin/bash

case "$(/usr/sbin/pidof command | /usr/sbin/wc -w)" in

0)  echo "Restarting command:     $(date)" >> log

    /usr/bin/sh x.sh
    ;;

4)  # all ok

    echo "All OK" >> log
    ;;

*)  for pid in $(/usr/sbin/ps -ef | /usr/sbin/grep "x" | /usr/sbin/grep "y" | /usr/sbin/awk '{print $2}'); do kill -9 $pid; done

    echo "Removed PIDs and RESTARTING FFMPEG: $(date)" >> /root/afarinEidSTs/log

    /usr/bin/sh x.sh
    ;;

esac

Double check full paths in your system.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.