Trying to do a loop with this script below. It works if I break it by deleting Google Chrome from Applications. If I put Chrome back into place it continuously kills the dock and says No matching processes belonging to you were found. Do I have to add something to killall Dock to exit the script or is Done in the wrong spot? Tried multiple things without any luck. Eventually want it to try every 15 minutes until all apps are in Applications and kill the dock so the shortcuts show instead of Question marks. This will happen once all apps get installed and Dock gets restarted.
i=0
while [ $i -lt 4 ]
do
if [[ -d "/Applications/Company Portal.app" && -d "/Applications/Google Chrome.app" ]];
then
killall Dock
else
i=$((i + 1)) | echo "Will tray again...."
sleep 10
fi
done
Update Here is what I eventually came up with, yea messy! But works! Will have to look at it more after see the responses here though.
echo $(date)
# Check to see if script has already run on computer before, if so, then exit.
file=/Users/Shared/.If_Installed_Restart_Dock_Has_Run.txt
if [ -e "$file" ]; then
echo "The If_Installed_Restart_Dock.sh script has run before and exiting..." && exit 0
else
touch /Users/Shared/.If_Installed_Restart_Dock_Has_Run.txt
fi
i=0
while [ $i -lt 6 ]
do
if [[ -d "/Applications/Google Chrome.app" && -d "/Applications/Microsoft Edge.app" ]];
then
killall Dock && exit 0
else
echo "Applications still need installed in order to restart Dock, will check again in 10 minutes for up to an hour, intune will try again in 8hrs..."
fi
i=$((i + 1))
sleep 600
done
Chrome is irrelevant. You're falling victim to the classic blunder. Consider:
#!/bin/bash
i=0
while [ $i -lt 4 ]; do
if echo "in first if, i = $i"; false ; then
echo bar
else
echo "in else, i = $i"
i=$((i + 1)) | echo "Will tray again...." # (1)
echo "after echo i = $i"
i=$((i + 1))
echo "after 2nd echo i = $i"
fi
done
In the above code, the i=$((i + 1)) in line (1) does not increment the variable used in the control loop. Since that command is in a pipe, it is executed in a subshell, and the variable i in the main shell is not incremented. It would probably be better to structure your code as:
#!/bin/sh
i=0
while [ $((i++)) -lt 4 ]; do
if [ -d "/Applications/Company Portal.app" ] && [ -d "/Applications/Google Chrome.app" ]; then
killall Dock
else
echo "Will tray again...."
sleep 10
fi
done
or
#!/bin/bash
for (( i = 0; i < 4; i++ )); do
if [ -d "/Applications/Company Portal.app" ] && [ -d "/Applications/Google Chrome.app" ]; then
killall Dock
else
echo "Will tray again...."
sleep 10
fi
done
Related
I want to write a script to run a program after X seconds, it can be stopped if user press Enter
But it cannot detect whether user pressed Enter key or no input
#!/bin/bash
seconds=$((5))
holder='000'
while [ $seconds -gt 0 ]; do
if [[ $holder = "" ]]; then
echo "Stop"
exit
else
echo "Start in $seconds seconds, Press Enter to stop"
fi
IFS= read -r -t 1 -n 1 -s holder && var="$holder"
: $((seconds--))
done
echo Start
If timeout happens, read fails (i.e. returns a non-zero return code). So it is as simple as this:
if read -t 1
then
echo Enter pressed
else
echo Timeout happened
fi
So in your case, something like this, maybe?
seconds=5
while [[ "$seconds" -gt 0 ]]; do
echo "Start in $seconds seconds, Press Enter to stop"
if read -t 1 -s
then
echo Stop
exit
else
((seconds--))
fi
done
echo Start
I want to apply dark theme depending on if it is "AM" or "PM". So I have created a bash script with "while loop" (So that it runs forever).
But running this script causes speed up in cpu fan. (that happens when our pc struggles to do something highly computational or playing game or anything heavy).
My script is just a simple line. So how can I run this script without causing high fan speeding?
#!/bin/bash
isNightThemeApplied=0
isDayThemeApplied=0
while [[ 1 -le 1 ]]
do
if [[ `date +%r` == *"AM"* ]]
then
if [[ isNightThemeApplied -eq 0 ]]
then
echo "Applying Night Theme..."
lookandfeeltool -a 'org.kde.breezedark.desktop'
isNightThemeApplied=1
isDayThemeApplied=0
echo "Night Theme Applied Successfully"
fi
else
if [[ isDayThemeApplied -eq 0 ]]
then
echo "Applying Day Theme..."
lookandfeeltool -a 'org.kde.breeze.desktop'
isDayThemeApplied=1
isNightThemeApplied=0
echo "Day Theme Applied Successfully"
fi
fi
done
You could do something like this that uses a while loop every 30 minutes so hardly resource hungry, no need to echo anything in my opinion, just put this in your start up script and run it.
#!/usr/bin/env bash
a=$(date +%p)
b="PM"
c="AM"
theme_change () {
if [[ "$a" == "$b" ]] ; then
lookandfeeltool -a 'org.kde.breezedark.desktop'
elif [[ "$a" == "$c" ]] ; then
lookandfeeltool -a 'org.kde.breeze.desktop'
fi
}
while true; do
theme_change;
sleep 1800;
done
I'm writing a shell script to make a new save file for the game risk of rain. I'm trying to make it so that each section of the unlocks that are available, such as achievements, monster logs, artifacts, etc. can either be added all at once to the file, or the user will be able to pick which ones they want added. I am new to writing shell scripts and I am not quite sure why I am getting the error syntax error near unexpected token `}' when I run what I have so far of my script. If anyone could explain to me as to why I am getting the error, how to fix it, and/or how to improve my script, it would be greatly appreciated. Also I am on Mac OS X if that matters. Here is my script.
#!/bin/bash
mkdir ~/Desktop/ror_save_unlock_all
echo "This script takes ~/Library/Application Support/com.riskofrain.riskofrain/Save.ini and backs it up to ~/Desktop/ror_save_unlock_all/originalSave. It generates a new Save.ini that is built to your specifications, unlocking all items and achievements or just the ones you choose, and replaces the existing Save.ini with the new one." >> ~/Desktop/ror_save_unlock_all/README.txt
mkdir ~/Desktop/ror_save_unlock_all/originalSave
cp ~/Library/Application\ Support/com.riskofrain.riskofrain/Save.ini ~/Desktop/ror_save_unlock_all/originalSave/
cd ~/Desktop/ror_save_unlock_all
echo -n 'How would you like the new Save.ini to be built? Press 1 for all unlocks or 2 to customize.'
read text
if [ $text = "1" ]
then
{
echo "[Achievement]" >> EOF1
count=1
while [ $count -lt 55 ]
do
echo "acheivement${count}=\"2\"" >> EOF2
count=`expr $count + 1`
done
echo "[Record]" >> EOF3
count=1
while [ $count -lt 31 ]
do
echo "mons${count}=\"1\"" >> EOF4
count=`expr $count + 1`
done
count=1
while [ $count -lt 110 ]
do
echo "item${count}=\"1\"" >> EOF5
count=`expr $count + 1`
done
count=1
while [ $count -lt 10 ]
do
echo "artifact${count}=\"1\"" >> EOF6
count=`expr $count + 1`
done
cat EOF1 EOF2 EOF3 EOF4 EOF5 EOF6 > Save.ini
rm EOF1 EOF2 EOF3 EOF4 EOF5 EOF6
cp -force ~/Desktop/ror_save_unlock_all/Save.ini ~/Library/Application\ Support/com.riskofrain.riskofrain/Save.ini
echo "Original Save.ini successfully overwritten."
exit
}
elif [ $text = "2" ]; then
{
echo "You selected customize. Now we will build a custom Save.ini"
echo -n "Press 1 if you want to unlock all achievements, press 2 to continue without unlocking all achievements."
read text
if [ $text = "1" ]; then
{
echo "[Achievement]" >> EOF1
count=1
while [ $count -lt 55 ]
do
echo "acheivement${count}=\"2\"" >> EOF2
count=`expr $count + 1`
done
echo "All achievements successfully unlocked."
echo -n "Press 1 to make the Save.ini and replace the existing one with it and then exit, or press 2 to customize it further."
read text
if [ $text = "1" ]; then
{
cat EOF1 EOF2 > Save.ini
rm EOF1 EOF2
cp -force ~/Desktop/ror_save_unlock_all/Save.ini ~/Library/Application\ Support/com.riskofrain.riskofrain/Save.ini
echo "Original Save.ini successfully overwritten."
exit
}
elif [ $text = "2" ] then;
{
echo -n "Press 1 to unlock all monster logs, or press 2 to continue without unlocking all monster logs."
read text
if [ $text = "1" ]; then
{
echo "[Record]" >> EOF3
count=1
while [ $count -lt 31 ]
do
echo "mons${count}=\"1\"" >> EOF4
count=`expr $count + 1`
done
echo "All achievements successfully unlocked."
echo -n "Press 1 to make the Save.ini and replace the existing one with it and then exit, or press 2 to customize it further."
read text
}
}
}
}
Your script has some error:
- Line 93: elif [ $text = "2" ] then; should change to elif [ $text = "2" ]; then
- If command in bash must have fi to close a condition. You can refer to http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-6.html
Hope this help
Before deciding to write a script, you should have a basic understanding of the language in which you're writing. Even the most cursory reading of the documentation or any how-to pages would have told you the correct syntax for an if statement.
Beyond that, you have a number of inefficiencies in your script. The backtick operator starts a subshell, a new instance of bash, so this is not necessarily something you want to be doing 110 times in a loop.
Here are a couple of your bigger problems fixed. I'd suggest looking into functions to eliminate a lot of code repetition and conditional nesting.
#!/bin/bash
mkdir ~/Desktop/ror_save_unlock_all
echo "This script takes ~/Library/Application Support/com.riskofrain.riskofrain/Save.ini and backs it up to ~/Desktop/ror_save_unlock_all/originalSave. It generates a new Save.ini that is built to your specifications, unlocking all items and achievements or just the ones you choose, and replaces the existing Save.ini with the new one." >> ~/Desktop/ror_save_unlock_all/README.txt
mkdir ~/Desktop/ror_save_unlock_all/originalSave
cp ~/Library/Application\ Support/com.riskofrain.riskofrain/Save.ini ~/Desktop/ror_save_unlock_all/originalSave/
cd ~/Desktop/ror_save_unlock_all
read -n 1 -p 'How would you like the new Save.ini to be built? Press 1 for all unlocks or 2 to customize.' text
if [ $text = "1" ]
then
echo "[Achievement]" > Save.ini
for count in {1..54}; do
echo "acheivement${count}=\"2\"" >> Save.ini
done
echo "[Record]" >> Save.ini
for count in {1..30}; do
echo "mons${count}=\"1\"" >> Save.ini
done
for count in {1..109}; do
echo "item${count}=\"1\"" >> Save.ini
done
for count in {1..9}; do
echo "artifact${count}=\"1\"" >> Save.ini
done
cp -force ~/Desktop/ror_save_unlock_all/Save.ini ~/Library/Application\ Support/com.riskofrain.riskofrain/Save.ini
echo "Original Save.ini successfully overwritten."
exit
elif [ $text = "2" ]; then
echo "You selected customize. Now we will build a custom Save.ini"
read -n 1 -p "Press 1 if you want to unlock all achievements, press 2 to continue without unlocking all achievements." text
if [ $text = "1" ]; then
echo "[Achievement]" > Save.ini
for count in {1..54}; do
echo "acheivement${count}=\"2\"" >> Save.ini
done
echo "All achievements successfully unlocked."
read -n 1 -p "Press 1 to make the Save.ini and replace the existing one with it and then exit, or press 2 to customize it further." text
if [ $text = "1" ]; then
cp -force ~/Desktop/ror_save_unlock_all/Save.ini ~/Library/Application\ Support/com.riskofrain.riskofrain/Save.ini
echo "Original Save.ini successfully overwritten."
exit
elif [ $text = "2" ]; then
read -n 1 -p "Press 1 to unlock all monster logs, or press 2 to continue without unlocking all monster logs." text
if [ $text = "1" ]; then
echo "[Record]" >> Save.ini
for count in {1..30}; do
echo "mons${count}=\"1\"" >> Save.ini
done
echo "All monster logs successfully unlocked."
read -n 1 -p "Press 1 to unlock all monster logs, or press 2 to continue without unlocking all monster logs." text
if [ $text = "1" ]; then
#...
fi
fi
fi
fi
fi
I am trying to make an application for the Mac App Store that will shut down/sleep the Mac after a user-set time. I have tried to use AppleScript, but that won't work if I am going to use it in Sandbox mode, I have tried to Google for a solution, but I cant seem to figure it out.
Hope someone can give me a hint or link to relevant documentation.
edit: made it more precise to what I desire to accomplish.
There is no way to do this. You may try to get a temporary-exception to run "shutdown" or "halt" thru BSD-layer but I doubt that such an app will pass the App Store review as these are tasks that require superuser / admin rights.
I wrote a script once. But I don't know whether it still works. Maybe it gives you at least a clue. Sleep still works - shutdown maybe causes problems if programs are blocking the shutdown.
(Not the prettiest code but it worked for me.)
#/bin/sh
#v1.0.0
#by Sapphire
echo "-----------------------------------------------------"
echo "* Sleep Timer *"
echo "-----------------------------------------------------"
echo "Please enter option: Sleep '1' or shutdown '0'"
echo -n "Option: "
read option
while :
do
if [ $option -eq 1 -o $option -eq 0 ]
then
break
fi
echo "<<ERROR: Only number: 1 or 0 allowed...>>"
echo "Please rnter option: Sleep '1' or shutdown '0'"
echo -n "Option: "
read option
done
echo "Please enter countdown (min):"
echo -n "Minutes: "
read shutDown
while :
do
if [ $shutDown -gt 0 -a $var -eq $var 2> /dev/null ]
then
break
fi
echo "<<ERROR: Positive number expected...>>"
echo "Please enter countdown (min):"
echo -n "Minutes: "
read shutDown
done
echo "*****************************************************"
echo "Counter has been started"
echo "'/!\ Kill countdown with CTRL-C /!\'"
echo -n "Envoking command in: "
date +"%H:%M %Z"
echo "*****************************************************"
if [ $option -eq 0 ]
then
echo "Shutdown in: "
fi
if [ $option -eq 1 ]
then
echo "Sleep in: "
fi
echo -e "\n *------------------------------* "
barCounter=0;
counter=0
((timeBarSize=$shutDown * 2))
bar="||||||||||||||||||||||||||||||"
barEmpty=" "
((flag=0))
for ((i=shutDown*60;i>=0;i--));
do
if ((counter >= timeBarSize ))
then
((counter=0))
((barCounter=$barCounter + 1))
fi
((counter=$counter + 1))
((timehh=$i/3600))
((timemm=$i/60 - timehh*60))
((timess=$i - timemm*60 - timehh*3600))
if (( flag == 1 ))
then
echo $(tput cuu1)$(tput el)$(tput cuu1)$(tput el)$(tput cuu1)$(tput el)$(tput cuu1)$(tput el)$(tput cuu1)
fi
((flag=1))
echo -e " | $timehh:$timemm:$timess |"
echo -e "\r *------------------------------* "
echo -e "\r *${bar:0:$barCounter}${barEmpty:$barCounter:30}* "
echo -e "\r *------------------------------* "
sleep 1;
done
if [ $option -eq 1 ]
then
echo "Going to sleep..."
sleep 1
osascript -e 'tell application "System Events" to sleep'
elif [ $option -eq 0 ];
then
echo "Shutting down..."
sleep 1
osascript -e 'tell application "System Events" to shut down'
else
echo "No valid command found... doing nothing!"
fi
I also had to add this in my '/etc/sudoers' file (CAUTION, if you don't know how to handle this file! -> google):
# Custom privilege
myUser ALL=NOPASSWD: /Users/myUser/Documents/sleepTimer.sh
What i want to do should be pretty simple, on my own i have reached the solution below, all i need is a few pointers to tell me if this is the way to do it or i should refactor anything in the code.
The below code, should create a few parallel processes and wait for them to finish executing then rerun the code again and again and again...
The script is triggered by a cron job once at 10 minutes, if the script is running, then do nothing, otherwise start the working process.
Any insight is highly appreciated since i am not that familiar with bash programming.
#!/bin/bash
# paths
THISPATH="$( cd "$( dirname "$0" )" && pwd )"
# make sure we move in the working directory
cd $THISPATH
# console init path
CONSOLEPATH="$( cd ../../ && pwd )/console.php"
# command line arguments
daemon=0
PHPPATH="/usr/bin/php"
help=0
# flag for binary search
LOOKEDFORPHP=0
# arguments init
while getopts d:p:h: opt; do
case $opt in
d)
daemon=$OPTARG
;;
p)
PHPPATH=$OPTARG
LOOKEDFORPHP=1
;;
h)
help=$OPTARG
;;
esac
done
shift $((OPTIND - 1))
# allow only one process
processesLength=$(ps aux | grep -v "grep" | grep -c $THISPATH/send-campaigns-daemon.sh)
if [ ${processesLength:-0} -gt 2 ]; then
# The process is already running
exit 0
fi
if [ $help -eq 1 ]; then
echo "---------------------------------------------------------------"
echo "| Usage: send-campaigns-daemon.sh |"
echo "| To force PHP CLI binary : |"
echo "| send-campaigns-daemon.sh -p /path/to/php-cli/binary |"
echo "---------------------------------------------------------------"
exit 0
fi
# php executable path, find it if not provided
if [ $PHPPATH ] && [ ! -f $PHPPATH ] && [ $LOOKEDFORPHP -eq 0 ]; then
phpVariants=( "php-cli" "php5-cli" "php5" "php" )
LOOKEDFORPHP=1
for i in "${phpVariants[#]}"
do
which $i >/dev/null 2>&1
if [ $? -eq 0 ]; then
PHPPATH=$(which $i)
fi
done
fi
if [ ! $PHPPATH ] || [ ! -f $PHPPATH ]; then
# Did not find PHP
exit 1
fi
# load options from app
parallelProcessesPerCampaign=3
campaignsAtOnce=10
subscribersAtOnce=300
sleepTime=30
function loadOptions {
local COMMAND="$PHPPATH $CONSOLEPATH option get_option --name=%s --default=%d"
parallelProcessesPerCampaign=$(printf "$COMMAND" "system.cron.send_campaigns.parallel_processes_per_campaign" 3)
campaignsAtOnce=$(printf "$COMMAND" "system.cron.send_campaigns.campaigns_at_once" 10)
subscribersAtOnce=$(printf "$COMMAND" "system.cron.send_campaigns.subscribers_at_once" 300)
sleepTime=$(printf "$COMMAND" "system.cron.send_campaigns.pause" 30)
parallelProcessesPerCampaign=$($parallelProcessesPerCampaign)
campaignsAtOnce=$($campaignsAtOnce)
subscribersAtOnce=$($subscribersAtOnce)
sleepTime=$($sleepTime)
}
# define the daemon function that will stay in loop
function daemon {
loadOptions
local pids=()
local k=0
local i=0
local COMMAND="$PHPPATH -q $CONSOLEPATH send-campaigns --campaigns_offset=%d --campaigns_limit=%d --subscribers_offset=%d --subscribers_limit=%d --parallel_process_number=%d --parallel_processes_count=%d --usleep=%d --from_daemon=1"
while [ $i -lt $campaignsAtOnce ]
do
while [ $k -lt $parallelProcessesPerCampaign ]
do
parallelProcessNumber=$(( $k + 1 ))
usleep=$(( $k * 10 + $i * 10 ))
CMD=$(printf "$COMMAND" $i 1 $(( $subscribersAtOnce * $k )) $subscribersAtOnce $parallelProcessNumber $parallelProcessesPerCampaign $usleep)
$CMD > /dev/null 2>&1 &
pids+=($!)
k=$(( k + 1 ))
done
i=$(( i + 1 ))
done
waitForPids pids
sleep $sleepTime
daemon
}
function daemonize {
$THISPATH/send-campaigns-daemon.sh -d 1 -p $PHPPATH > /dev/null 2>&1 &
}
function waitForPids {
stillRunning=0
for i in "${pids[#]}"
do
if ps -p $i > /dev/null
then
stillRunning=1
break
fi
done
if [ $stillRunning -eq 1 ]; then
sleep 0.5
waitForPids pids
fi
return 0
}
if [ $daemon -eq 1 ]; then
daemon
else
daemonize
fi
exit 0
when starting a script, create a lock file to know that this script is running. When the script finish, delete the lock file. If somebody kill the process while it is running, the lock file remain forever, though test how old it is and delete after if older than a defined value. For example,
#!/bin/bash
# 10 min
LOCK_MAX=600
typedef LOCKFILE=/var/lock/${0##*/}.lock
if [[ -f $LOCKFILE ]] ; then
TIMEINI=$( stat -c %X $LOCKFILE )
SEGS=$(( $(date +%s) - $TIEMPOINI ))
if [[ $SEGS -gt $LOCK_MAX ]] ; then
reportLocking or somethig to inform you
# Kill old intance ???
OLDPID=$(<$LOCKFILE)
[[ -e /proc/$OLDPID ]] && kill -9 $OLDPID
# Next time that the program is run, there is no lock file and it will run.
rm $LOCKFILE
fi
exit 65
fi
# Save PID of this instance to the lock file
echo "$$" > $LOCKFILE
### Your code go here
# Remove the lock file before script finish
[[ -e $LOCKFILE ]] && rm $LOCKFILE
exit 0
from here:
#!/bin/bash
...
echo PARALLEL_JOBS:${PARALLEL_JOBS:=1}
declare -a tests=($(.../find_what_to_run))
echo "${tests[#]}" | \
xargs -d' ' -n1 -P${PARALLEL_JOBS} -I {} bash -c ".../run_that {}" || { echo "FAILURE"; exit 1; }
echo "SUCCESS"
and here you can nick the code for portable locking with fuser
Okay, so i guess i can answer to my own question with a proper answer that works after many tests.
So here is the final version, simplified, without comments/echo :
#!/bin/bash
sleep 2
DIR="$( cd "$( dirname "$0" )" && pwd )"
FILE_NAME="$( basename "$0" )"
COMMAND_FILE_PATH="$DIR/$FILE_NAME"
if [ ! -f "$COMMAND_FILE_PATH" ]; then
exit 1
fi
cd $DIR
CONSOLE_PATH="$( cd ../../ && pwd )/console.php"
PHP_PATH="/usr/bin/php"
help=0
LOOKED_FOR_PHP=0
while getopts p:h: opt; do
case $opt in
p)
PHP_PATH=$OPTARG
LOOKED_FOR_PHP=1
;;
h)
help=$OPTARG
;;
esac
done
shift $((OPTIND - 1))
if [ $help -eq 1 ]; then
printf "%s\n" "HELP INFO"
exit 0
fi
if [ "$PHP_PATH" ] && [ ! -f "$PHP_PATH" ] && [ "$LOOKED_FOR_PHP" -eq 0 ]; then
php_variants=( "php-cli" "php5-cli" "php5" "php" )
LOOKED_FOR_PHP=1
for i in "${php_variants[#]}"
do
which $i >/dev/null 2>&1
if [ $? -eq 0 ]; then
PHP_PATH="$(which $i)"
break
fi
done
fi
if [ ! "$PHP_PATH" ] || [ ! -f "$PHP_PATH" ]; then
exit 1
fi
LOCK_BASE_PATH="$( cd ../../../common/runtime && pwd )/shell-pids"
LOCK_PATH="$LOCK_BASE_PATH/send-campaigns-daemon.pid"
function remove_lock {
if [ -d "$LOCK_PATH" ]; then
rmdir "$LOCK_PATH" > /dev/null 2>&1
fi
exit 0
}
if [ ! -d "$LOCK_BASE_PATH" ]; then
if ! mkdir -p "$LOCK_BASE_PATH" > /dev/null 2>&1; then
exit 1
fi
fi
process_running=0
if mkdir "$LOCK_PATH" > /dev/null 2>&1; then
process_running=0
else
process_running=1
fi
if [ $process_running -eq 1 ]; then
exit 0
fi
trap "remove_lock" 1 2 3 15
COMMAND="$PHP_PATH $CONSOLE_PATH option get_option --name=%s --default=%d"
parallel_processes_per_campaign=$(printf "$COMMAND" "system.cron.send_campaigns.parallel_processes_per_campaign" 3)
campaigns_at_once=$(printf "$COMMAND" "system.cron.send_campaigns.campaigns_at_once" 10)
subscribers_at_once=$(printf "$COMMAND" "system.cron.send_campaigns.subscribers_at_once" 300)
sleep_time=$(printf "$COMMAND" "system.cron.send_campaigns.pause" 30)
parallel_processes_per_campaign=$($parallel_processes_per_campaign)
campaigns_at_once=$($campaigns_at_once)
subscribers_at_once=$($subscribers_at_once)
sleep_time=$($sleep_time)
k=0
i=0
pp=0
COMMAND="$PHP_PATH -q $CONSOLE_PATH send-campaigns --campaigns_offset=%d --campaigns_limit=%d --subscribers_offset=%d --subscribers_limit=%d --parallel_process_number=%d --parallel_processes_count=%d --usleep=%d --from_daemon=1"
while [ $i -lt $campaigns_at_once ]
do
while [ $k -lt $parallel_processes_per_campaign ]
do
parallel_process_number=$(( $k + 1 ))
usleep=$(( $k * 10 + $i * 10 ))
CMD=$(printf "$COMMAND" $i 1 $(( $subscribers_at_once * $k )) $subscribers_at_once $parallel_process_number $parallel_processes_per_campaign $usleep)
$CMD > /dev/null 2>&1 &
k=$(( k + 1 ))
pp=$(( pp + 1 ))
done
i=$(( i + 1 ))
done
wait
sleep ${sleep_time:-30}
$COMMAND_FILE_PATH -p "$PHP_PATH" > /dev/null 2>&1 &
remove_lock
exit 0
Usually, it is a lock file, not a lock path. You hold the PID in the lock file for monitoring your process. In this case your lock directory does not hold any PID information. Your script also does not do any PID file/directory maintenance when it starts in case of a improper shutdown of your process without cleaning of your lock.
I like your first script better with this in mind. Monitoring the PID's running directly is cleaner. The only problem is if you start a second instance with cron, it is not aware of the PID's connect to the first instance.
You also have processLength -gt 2 which is 2, not 1 process running so you will duplicate your process threads.
It seems also that daemonize is just recalling the script with daemon which is not very useful. Also, having a variable with the same name as a function is not effective.
The correct way to make a lockfile is like this:
# Create a temporary file
echo $$ > ${LOCKFILE}.tmp$$
# Try the lock; ln without -f is atomic
if ln ${LOCKFILE}.tmp$$ ${LOCKFILE}; then
# we got the lock
else
# we didn't get the lock
fi
# Tidy up the temporary file
rm ${LOCKFILE}.tmp$$
And to release the lock:
# Unlock
rm ${LOCKFILE}
The key thing is to create the lock file to one side, using a unique name, and then try to link it to the real name. This is an atomic operation, so it should be safe.
Any solution that does "test and set" gives you a race condition to deal with. Yes, that can be sorted out, but you end up write extra code.