I\'m an absolute beginner and am trying to create a bash script to randomize the start and exit of a command line app. I plan to autostart the script on boot (Crunchbang) after
Try this code for your randomizer.sh
min_val=60
range=150
while true ; do
run_this_command &
last_pid=$!
sleep $[ ( $RANDOM % $range ) + $min_val ]
{ [ "$(ps -p $last_pid -o comm= )" ] && \
[ "$(ps -p $last_pid -o comm= )" = run_this_command ];
} && { kill -KILL $last_pid ;}
done
Some notes:
{ [ condition ] && { command ;} && command
runs faster than if [ condition ]; then command, else command; fi
ps -p $last_pid -o comm=
will spit out the name of the process with the PID of $last_pid
. If there is no PID with that value then its exist code is 1. Amended to meet the additional random wait period before start requirement:
# Minimum and range values for random Wait before start in seconds
MinA=60;RangeA=150
# Minimum and range values for random Wait before kill in seconds
MinB=60; RangeB=150 #
while true ; do
sleep $[ ( $RANDOM % $RangeA ) + $MinA ]
run_this_command &
last_pid=$!
sleep $[ ( $RANDOM % $RangeB ) + $MinB ]
{ [ "$(ps -p $last_pid -o comm= )" ] && \
[ "$(ps -p $last_pid -o comm= )" = run_this_command ]
} && \{ kill -KILL $last_pid ;}
done