I am trying to write a bash script that detects if a service has changed state. I have this so far:
while true; do
if [ -z "$(netstat -tulpn | grep 51827)" ];
then
echo notinuse
else
echo inuse
fi
sleep 5
done
It works but it will endlessly write when the service is up or down, and I only want it to report on the first instance of a state change. So report when the service was down, and then up as well as when it was up and then went down.
I started to create loop counters and comparing to a previous run but I got into a complete mess of variables. Can anyone help?
if [ -z "$(netstat -tulpn | grep 51827)" ];
then
echo notinuse
notify_status="notinuse-sent"
else
echo inuse
notify_status="inuse-sent"
fi
while true; do
if [ -z "$(netstat -tulpn | grep 51827)" ];
then
if [ $notify_status = "notinuse-sent" ]; then
echo "already notified"
else
echo notinuse
$notify_status="notinuse-sent"
fi
else
if [ $notify_status = "inuse-sent" ]; then
echo "already notified"
else
echo inuse
$notify_status="inuse-sent"
fi
fi
sleep 5
done
Related
I'm trying to monitor the rstudio-server.status using a bash script and cron it to run every 5minutes and push the status of the service to a logfile. But, somehow i'm unable to get the status of the service.
service=rstudio-server.service
if [[ $(systemctl status $service)]] ; then
echo "$service is running !! nothing to worry!"
else
/usr/lib/$service start
fi
is this a goodway to monitor?
got it a long back ago, posting it now.
Thank you all!
#!/bin/bash
# Shell-guy to monitor a process (0~0)
#<script.sh> "service_name"
service=$1
if [ "$(systemctl status $service | grep -c "active (running)")" -gt 0 ];then
echo "$service is running !!"
elif [ "$(systemctl status $service | grep -c "active (running)")" -eq 0 ];then
echo "$service is not running"
$service restart
if [ "$(systemctl status $service | grep -c "active (running)")" -lt 1 ];then
$service restart
elif [ "$(systemctl status $service | grep -c "active (running)")" -eq 0 ];then
echo "The service is not found!!"
fi
fi
Question: How do you check if a PID exists and use the result within an IF statement in bash?
Things I've tried
if [ "$(ps -p $pid)" -eq 0 ]; then
echo "Running"
else
echo "Not Running"
fi
if [ "$(kill -0 $pid)" -eq 0 ]; then
echo "Running"
else
echo "Not Running"
fi
Neither of these evaluate correctly no matter how I redirect STDOUT/STDER
How do you check if a PID exists and use the result within an if statement?
You can capture the output in a variable and then check the exit status:
output=$(ps -p "$pid")
if [ "$?" -eq 0 ]; then
echo "Found"
echo "$output"
fi
Just remember that $? is getting reset every time you run a command, so something like the following wont work:
output=$(ps -p "$pid")
echo "$output"
# Now $? will be refering to the exit status of echo
if [ "$?" -eq 0 ]; then
echo "Found"
fi
One can also stick everything together in the if statement:
if output=$(ps -p "$pid")
then
echo "Found: $output"
fi
Make it dynamic by passing the pid you want to check:
#!/usr/local/bin/bash
if ps -p $1 > /dev/null;
then
echo "running"
else
echo "not running"
fi
Example runs:
What's your host OS?
If you have /proc then this may work for you:
if [ -d "/proc/$pid" ]; then
echo "Running"
else
echo "Not running"
fi
I tried learning how to write a bash script to have my own script to start and stop a Tomcat Server, and I can't seem to find what is causing the error in this script. I've double checked my if and fi statements to make sure they match, but still have no idea what is wrong.
EDIT:
Here is the exact error message
line 87: syntax error: unexpected end of file
Here is the script:
#!/bin/bash
#Returns the process id of the Tomcat server if currently running
function tomcat_pid {
local pid=0
local temp=$(ps x | grep "$CATALINA_HOME" | grep -v grep | cut -d ' ' -f 1)
if [ -n "$temp" ]; then
pid=$temp
fi
echo "$pid"
}#tomcat_pid
#Checks the status of the Tomcat Server
function tomcat_status {
local retval="Tomcat Server is not currently running"
local pid
pid=$(tomcat_pid)
if [ "$pid" -gt 0 ]; then
retval="Tomcat Server is running at pid: $pid"
fi
echo "$retval"
}#tomcat_status
#Starts the Tomcat Server
function tomcat_start {
local pid
pid=$(tomcat_pid)
if [ "$pid" -gt 0 ]; then
echo "Tomcat Server already running at pid: $pid"
else
echo "Starting Tomcat Server"
"$CATALINA_HOME/bin/startup.sh"
fi
}#tomcat_start
#Stops the Tomcat Server
function tomcat_stop {
local pid
pid=$(tomcat_pid)
if [ "$pid" -gt 0 ]; then
echo "Shutting down Tomcat Server"
"$CATALINA_HOME/bin/shutdown.sh"
else
echo "Tomcat Server is not currently running"
fi
}#tomcat_stop
#Restarts the Tomcat Server
function tomcat_restart {
local pid
pid=$(tomcat_pid)
if [ "$pid" -gt 0 ]; then
echo "Restarting the Tomcat Server"
"$CATALINA_HOME/bin/shutdown.sh"
sleep 5s
"$CATALINA_HOME/bin/start.sh"
else
echo "Starting the Tomcat Server"
"$CATALINA_HOME/bin/startup.sh"
fi
}#tomcat_restart
if [ -n "$1" ]; then
if [ "$1" = 'restart' ]; then
tomcat_restart
#tomcat start - Starts the Tomcat Server
elif [ "$1" = 'start' ]; then
tomcat_start
#tomcat shutdown - Shuts down the Tomcat Server
elif [ "$1" = 'shutdown' ]; then
tomcat_stop
#tomcat status - Checks the status of the tomcat server
elif [ "$1" = 'status' ]; then
tomcat_status
else
echo "Please use correct options"
fi
else
echo "Please use correct options"
fi
See man bash, in other words bash(1), Section SHELL GAMMAR
{ list; }
list is simply executed in the current shell environment. list must be terminated with a newline or semi‐
colon. This is known as a group command. The return status is the exit status of list. Note that unlike
the metacharacters ( and ), { and } are reserved words and must occur where a reserved word is permitted to
be recognized. Since they do not cause a word break, they must be separated from list by whitespace or
another shell metacharacter.
The last sentence points at your problem.
I'm new in Shellscript, and i'm getting some problems. I need a script to check if the services are running or not, if its not running, and dont exist the flag, start all services. What i'm doing wrong?
#!/bin/bash
file= "$PIN_HOME/apps/DE_BILL_MI_BRM/alarmistica/flags/intervencao.flag"
# Check if services are running
for service in $BRM_SERVICES
do
if [ps -ef | grep $service | grep -v grep | awk 'NR>1{for (i=1;i<=NF;i++)if($i==1) print "Services not running", i}' ]; then
echo $service " is not running correctly"
else
if [ -f "$file" ]; then
echo "Flag exists. The service will not start"
else
echo "$file not found. Starting all services"
pin_ctl start all
fi
fi
done
When ($i==1), the services is not running!
But the results is not corresponding. For exemple, when the services are down, the script dont start the services...
For checking process tables, use pgrep instead.
#!/bin/bash
file= "$PIN_HOME/apps/DE_BILL_MI_BRM/alarmistica/flags/intervencao.flag"
# Check if services are running
for service in $BRM_SERVICES
do
pgrep -f "$service";
exstat=$?; # This checks the exit status
if [ "$exstat" -eq 0 ] && ! [ -f "$file" ]; then
echo "pgrep returned exit status $extstat";
else
echo "$file not found. Starting all services"
pin_ctl start all
fi
done
We have to cache quite a big database of data after each upload, so we created a bash script that should handle it for us. The script should start 4 paralel curls to the site and once they're done, start the next one from the URL list we store in the file.
In theory everything works ok, and the concept works if we run the run 4 processes from our local machines to the target site.
If i set the MAX_NPROC=1 the curl takes as long as it would if the browser hits the URL
i.e. 20s
If I set the MAX_NPROC=2 the time request took, triples.
Am I missing something? Is that an apache setting that is slowing us down? or is this a secret cURL setting that I'm missing?
Any help will be appreciated. Please find the bash script below
#!/bin/bash
if [[ -z $2 ]]; then
MAX_NPROC=4 # default
else
MAX_NPROC=$2
fi
if [[ -z $1 ]]; then
echo "File with URLs is missing"
exit
fi;
NUM=0
QUEUE=""
DATA=""
URL=""
declare -a URL_ARRAY
declare -a TIME_ARRAY
ERROR_LOG=""
function queue {
QUEUE="$QUEUE $1"
NUM=$(($NUM+1))
}
function regeneratequeue {
OLDREQUEUE=$QUEUE
echo "OLDREQUEUE:$OLDREQUEUE"
QUEUE=""
NUM=0
for PID in $OLDREQUEUE
do
process_count=`ps ax | awk '{print $1 }' | grep -c "^${PID}$"`
if [ $process_count -eq 1 ] ; then
QUEUE="$QUEUE $PID"
NUM=$(($NUM+1))
fi
done
}
function checkqueue {
OLDCHQUEUE=$QUEUE
for PID in $OLDCHQUEUE
do
process_count=`ps ax | awk '{print $1 }' | grep -c "^${PID}$"`
if [ $process_count -eq 0 ] ; then
wait $PID
my_status=$?
if [[ $my_status -ne 0 ]]
then
echo "`date` $my_status ${URL_ARRAY[$PID]}" >> $ERROR_LOG
fi
current_time=`date +%s`
old_time=${TIME_ARRAY[$PID]}
time_difference=$(expr $current_time - $old_time)
echo "`date` ${URL_ARRAY[$PID]} END ($time_difference seconds)" >> $REVERSE_LOG
#unset TIME_ARRAY[$PID]
#unset URL_ARRAY[$PID]
regeneratequeue # at least one PID has finished
break
fi
done
}
REVERSE_LOG="$1.rvrs"
ERROR_LOG="$1.error"
echo "Cache STARTED at `date`" > $REVERSE_LOG
echo "" > ERROR_LOG
while read line; do
# create the command to be run
DATA="username=user#server.com&password=password"
URL=$line
CMD=$(curl --data "${DATA}" -s -o /dev/null --url "${URL}")
echo "Command: ${CMD}"
# Run the command
$CMD &
# Get PID for process
PID=$!
queue $PID;
URL_ARRAY[$PID]=$URL;
TIME_ARRAY[$PID]=`date +%s`
while [ $NUM -ge $MAX_NPROC ]; do
checkqueue
sleep 0.4
done
done < $1
echo "Cache FINISHED at `date`" >> $REVERSE_LOG
exit
The network is almost always the bottleneck. Spawning more connections usually makes it slower.
You can try to see if parallel'izing it will do you any good by spawning several
time curl ...... &