pidof -x $0 returns 2 instead of expected 1, is there a one-line alternative? - linux

In a bash script, I'm trying to use the following line to determine if another process is executing the current script:
/sbin/pidof -x $0 |wc -w
But the response is always 2, instead of the expected value of 1.
I've tried the following calls:
/sbin/pidof -x $0 returns 1 pid
/sbin/pidof -x $0 |wc -w returns 2
/sbin/pidof -x $0 |head returns 2 pids
/sbin/pidof -x $0 |head |wc -w returns 2
/sbin/pidof -x $0 |head |tail returns 2 pids
/sbin/pidof -x $0 |head |tail |wc -w returns 2
Can anyone suggest an alternative (or fix) to achieve what I'm trying to do, and explain why piping the output to anything causes pidof output to go "a bit funny"?
This is how the script currently uses pidof, which works fine:
RUNNING=`/sbin/pidof -x $0`
RUNNING=`echo -n ${RUNNING} | wc -w`
[[ ${RUNNING} -gt 1 ]] && return

If you are only trying to prevent a second running script the following will do the trick:
pid=/tmp/$(basename $0).pid
[ -e $pid ] && exit 0;
trap 'rm -f $pid >/dev/null 2>&1;' 0
trap 'exit 2' 1 2 3 15
touch $pid
Just start your script with those lines. Basically it checks for a file and stop execution if the file is present. Note that if you kill (-9) the running script you are responsible for cleaning up the pid file that was created. Kill (-9) bypasses the shell trap that would otherwise clean up the pid file.

Related

Binary operator expected error while running a while loop in bash

TL:DR
Check if a given PID is running, if yes kill the process.
count=0
while [[ "$count" -le 3 && ps -p $pid > /dev/null ]];
do
kill -9 $pid
count=$(( $count + 1 )):
done
To this I am getting an error as:
line 8: [: -p: binary operator expected
I am aware there are several similar questions, I already tried their solutions but it doesn't seem to work.
The while loop is logically incorrect, as #kvantour mentioned. Here is the script. Note that it will let you know if it could not kill the process, so you can investigate the root cause. The script gets PID as its first argument (e.g. $./kill-pid.sh 1234) Note that this works for bash ver. 4.1+:
#!/usr/bin/env bash
if ps -p $1 > /dev/null
then
output=$(kill -9 $1 2>&1)
if [ $? -ne 0 ]
then
echo "Process $1 cannot be killed. Reason:"
echo "$output"
# This line is added per OP request, to try to re-run the kill command if it failed for the first time.
# kill -9 $1
fi
fi

tail the last modified file and monitor for new files in bash

I can tail -f the last modified file using ls --sort=time | head -1 | xargs tail -f but I'm looking for something that would continuously run the first part as well, i.e. if a new files is created while the tail command is running it switches to tailing the new file. I thought about using watch command but that doesn't seem to work nicely with tail -f
It seems you need something like this:
#!/bin/bash
TAILPID=0
WATCHFILE=""
trap 'kill $(jobs -p)' EXIT # Makes sure we clean our mess (background processes) on exit
while true
do
NEWFILE=`ls --sort=time | head -n 1`
if [ "$NEWFILE" != "$WATCHFILE" ]; then
echo "New file has been modified"
echo "Now watching: $NEWFILE";
WATCHFILE=$NEWFILE
if [ $TAILPID -ne 0 ]; then
# Kill old tail
kill $TAILPID
wait $! &> /dev/null # supress "Terminated" message
fi
tail -f $NEWFILE &
TAILPID=$! # Storing tail PID so we could kill it later
fi
sleep 1
done

Does editing a file while some script is performing grep in it has any effect

Well I am trying to take some decision based on some text is not present in a file, but the problem is the file will be modified while my shell script is doing grep in it.
#!/bin/bash
grep -q "decision" /home/tejto/test/testingshell
ret_code=$?
while [ $ret_code -ne 0 ]
do
echo $ret_code
grep -q "decision" /home/tejto/test/testingshell
echo 'Inside While!'
sleep 5
done
echo 'Gotcha!'
The text "decision" is not present in file while this shell script is started, but when I modify this file by some other bash prompt and put the text 'decision' in it, in this case my script is not taking that change and it is keep on looping in while , so does that mean my shell script caches that particular file ?
Because you are setting ret_code variable only once outside loop and not setting it again inside the loop after next grep -q command.
To fix you will need:
grep -q "decision" /home/tejto/test/testingshell
ret_code=$?
while [ $ret_code -ne 0 ]
do
echo $ret_code
grep -q "decision" /home/tejto/test/testingshell
ret_code=$?
echo 'Inside While!'
sleep 5
done
echo 'Gotcha!'
OR you can shorten your script like this:
#!/bin/bash
while ! grep -q "decision" /home/tejto/test/testingshell
do
echo $?
echo 'Inside While!'
sleep 5
done
echo 'Gotcha!'
i.e. no need to use a variable and directly use grep -q in your while condition.
[EDIT:Tejendra]
#!/bin/bash
until grep -q "decision" /home/tejto/test/testingshell
do
echo $?
echo 'Inside While!'
sleep 5
done
echo 'Gotcha!'
This last solution would not use ret_code and give the desired result as first solution.

Linux Top command with more than 20 commands

I want to use top in order to monitor numerous processes by process name. I already know about doing $ top -p $(pgrep -d ',' <pattern>) but top only limits me to 20 pids. Is there a way to allow for more than 20 pids?
Do I have to use a combination of ps and watch to get similar results?
From top/top.c:
if (Monpidsidx >= MONPIDMAX)
error_exit(fmtmk(N_fmt(LIMIT_exceed_fmt), MONPIDMAX));
(where LIMIT_exceed_fmt is the error message you're getting).
And in top/top.h:
#define MONPIDMAX 20
I changed this number to 80, and that seems to work okay. Not sure why this hardcoded limit is so low.
So, if manually compiling procps-ng is an option, then you could do that. You don't need to replace the system top (or need root privileges), you can just put it in your homedir.
Another workaround might be using tmux or screen and multiple top instances.
Yet another possible solution might be using ps with a loop, ie.
#!/bin/sh
while :; do
clear
ps $*
sleep 1
done
Invoke it as: ./psloop.sh 42 666
You may want to add more flags to ps for additional info. Also be aware this is less efficient, since it will invoke 3 binaries every second.
A wrapper with watch. Tested with Ubuntu 11.04, Ubuntu 14.04, RHEL5, RHEL6 and RHEL7
Syntax: script.sh pid [ pid ...] # space separated
Example: script.sh $(pgrep -d ' ' <pattern>)
#!/bin/bash
i=10 # ~ interval in seconds
format()
{
a="$1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12}"
a="$a ${13} ${14} ${15} ${16} ${17} ${18} ${19} ${20}"
a="${a%%*( )}"; a="${a// /,}"
}
main()
{
format $#
top -b -n 1 -p $a
[ $# -gt 20 ] && shift 20 || shift $#
until [ $# -eq 0 ]; do
format $#
top -b -n 1 -p $a | sed '1,/PID/d;/^$/d'
[ $# -gt 20 ] && shift 20 || shift $#
done
}
if [ "$1" == "watch" ]; then
shift
shopt -s extglob
main $#
else
watch -t -n $i "$0 watch $#"
fi

Linux/Unix command to determine if process is running?

I need a platform independent (Linux/Unix|OSX) shell/bash command that will determine if a specific process is running. e.g. mysqld, httpd...
What is the simplest way/command to do this?
While pidof and pgrep are great tools for determining what's running, they are both, unfortunately, unavailable on some operating systems. A definite fail safe would be to use the following: ps cax | grep command
The output on Gentoo Linux:
14484 ? S 0:00 apache2
14667 ? S 0:00 apache2
19620 ? Sl 0:00 apache2
21132 ? Ss 0:04 apache2
The output on OS X:
42582 ?? Z 0:00.00 (smbclient)
46529 ?? Z 0:00.00 (smbclient)
46539 ?? Z 0:00.00 (smbclient)
46547 ?? Z 0:00.00 (smbclient)
46586 ?? Z 0:00.00 (smbclient)
46594 ?? Z 0:00.00 (smbclient)
On both Linux and OS X, grep returns an exit code so it's easy to check if the process was found or not:
#!/bin/bash
ps cax | grep httpd > /dev/null
if [ $? -eq 0 ]; then
echo "Process is running."
else
echo "Process is not running."
fi
Furthermore, if you would like the list of PIDs, you could easily grep for those as well:
ps cax | grep httpd | grep -o '^[ ]*[0-9]*'
Whose output is the same on Linux and OS X:
3519 3521 3523 3524
The output of the following is an empty string, making this approach safe for processes that are not running: echo ps cax | grep aasdfasdf | grep -o '^[ ]*[0-9]*'
This approach is suitable for writing a simple empty string test, then even iterating through the discovered PIDs.
#!/bin/bash
PROCESS=$1
PIDS=`ps cax | grep $PROCESS | grep -o '^[ ]*[0-9]*'`
if [ -z "$PIDS" ]; then
echo "Process not running." 1>&2
exit 1
else
for PID in $PIDS; do
echo $PID
done
fi
You can test it by saving it to a file (named "running") with execute permissions (chmod +x running) and executing it with a parameter: ./running "httpd"
#!/bin/bash
ps cax | grep httpd
if [ $? -eq 0 ]; then
echo "Process is running."
else
echo "Process is not running."
fi
WARNING!!!
Please keep in mind that you're simply parsing the output of ps ax which means that, as seen in the Linux output, it is not simply matching on processes, but also the arguments passed to that program. I highly recommend being as specific as possible when using this method (e.g. ./running "mysql" will also match 'mysqld' processes). I highly recommend using which to check against a full path where possible.
References:
http://linux.about.com/od/commands/l/blcmdl1_ps.htm
http://linux.about.com/od/commands/l/blcmdl1_grep.htm
You SHOULD know the PID !
Finding a process by trying to do some kind of pattern recognition on the process arguments (like pgrep "mysqld") is a strategy that is doomed to fail sooner or later. What if you have two mysqld running? Forget that approach. You MAY get it right temporarily and it MAY work for a year or two but then something happens that you haven't thought about.
Only the process id (pid) is truly unique.
Always store the pid when you launch something in the background. In Bash this can be done with the $! Bash variable. You will save yourself SO much trouble by doing so.
How to determine if process is running (by pid)
So now the question becomes how to know if a pid is running.
Simply do:
ps -o pid= -p <pid>
This is POSIX and hence portable. It will return the pid itself if the process is running or return nothing if the process is not running. Strictly speaking the command will return a single column, the pid, but since we've given that an empty title header (the stuff immediately preceding the equals sign) and this is the only column requested then the ps command will not use header at all. Which is what we want because it makes parsing easier.
This will work on Linux, BSD, Solaris, etc.
Another strategy would be to test on the exit value from the above ps command. It should be zero if the process is running and non-zero if it isn't. The POSIX spec says that ps must exit >0 if an error has occurred but it is unclear to me what constitutes 'an error'. Therefore I'm not personally using that strategy although I'm pretty sure it will work as well on all Unix/Linux platforms.
On most Linux distributions, you can use pidof(8).
It will print the process ids of all running instances of specified processes, or nothing if there are no instances running.
For instance, on my system (I have four instances of bashand one instance of remmina running):
$ pidof bash remmina
6148 6147 6144 5603 21598
On other Unices, pgrep or a combination of ps and grep will achieve the same thing, as others have rightfully pointed out.
This should work on most flavours of Unix, BSD and Linux:
PATH=/usr/ucb:${PATH} ps aux | grep httpd | grep -v grep
Tested on:
SunOS 5.10 [Hence the PATH=...]
Linux 2.6.32 (CentOS)
Linux 3.0.0 (Ubuntu)
Darwin 11.2.0
FreeBSD 9.0-STABLE
Red Hat Enterprise Linux ES release 4
Red Hat Enterprise Linux Server release 5
The simpliest way is to use ps and grep:
command="httpd"
running=`ps ax | grep -v grep | grep $command | wc -l`
if [ running -gt 0 ]; then
echo "Command is running"
else
echo "Command is not running"
fi
If your command has some command arguments, then you can also put more 'grep cmd_arg1' after 'grep $command' to filter out other possible processes that you are not interested in.
Example: show me if any java process with supplied argument:
-Djava.util.logging.config.file=logging.properties
is running
ps ax | grep -v grep | grep java | grep java.util.logging.config.file=logging.properties | wc -l
Putting the various suggestions together, the cleanest version I was able to come up with (without unreliable grep which triggers parts of words) is:
kill -0 $(pidof mysql) 2> /dev/null || echo "Mysql ain't runnin' message/actions"
kill -0 doesn't kill the process but checks if it exists and then returns true, if you don't have pidof on your system, store the pid when you launch the process:
$ mysql &
$ echo $! > pid_stored
then in the script:
kill -0 $(cat pid_stored) 2> /dev/null || echo "Mysql ain't runnin' message/actions"
Just a minor addition: if you add the -c flag to ps, you don't need to remove the line containing the grep process with grep -v afterwards. I.e.
ps acux | grep cron
is all the typing you'll need on a bsd-ish system (this includes MacOSX) You can leave the -u away if you need less information.
On a system where the genetics of the native ps command point back to SysV, you'd use
ps -e |grep cron
or
ps -el |grep cron
for a listing containing more than just pid and process name. Of course you could select the specific fields to print out using the -o <field,field,...> option.
I use pgrep -l httpd but not sure it is present on any platform...
Who can confirm on OSX?
This approach can be used in case commands 'ps', 'pidof' and rest are not available.
I personally use procfs very frequently in my tools/scripts/programs.
egrep -m1 "mysqld$|httpd$" /proc/[0-9]*/status | cut -d'/' -f3
Little explanation what is going on:
-m1 - stop process on first match
"mysqld$|httpd$" - grep will match lines which ended on mysqld OR httpd
/proc/[0-9]* - bash will match line which started with any number
cut - just split the output by delimiter '/' and extract field 3
You should know the PID of your process.
When you launch it, its PID will be recorded in the $! variable. Save this PID into a file.
Then you will need to check if this PID corresponds to a running process. Here's a complete skeleton script:
FILE="/tmp/myapp.pid"
if [ -f $FILE ];
then
PID=$(cat $FILE)
else
PID=1
fi
ps -o pid= -p $PID
if [ $? -eq 0 ]; then
echo "Process already running."
else
echo "Starting process."
run_my_app &
echo $! > $FILE
fi
Based on the answer of peterh. The trick for knowing if a given PID is running is in the ps -o pid= -p $PID instruction.
None of the answers worked for me, so heres mine:
process="$(pidof YOURPROCESSHERE|tr -d '\n')"
if [[ -z "${process// }" ]]; then
echo "Process is not running."
else
echo "Process is running."
fi
Explanation:
|tr -d '\n'
This removes the carriage return created by the terminal. The rest can be explained by this post.
This prints the number of processes whose basename is "chromium-browser":
ps -e -o args= | awk 'BEGIN{c=0}{
if(!match($1,/^\[.*\]$/)){sub(".*/","",$1)} # Do not strip process names enclosed by square brackets.
if($1==cmd){c++}
}END{print c}' cmd="chromium-browser"
If this prints "0", the process is not running. The command assumes process path does not contain breaking space. I have not tested this with suspended processes or zombie processes.
Tested using gwak as the awk alternative in Linux.
Here is a more versatile solution with some example usage:
#!/bin/sh
isProcessRunning() {
if [ "${1-}" = "-q" ]; then
local quiet=1;
shift
else
local quiet=0;
fi
ps -e -o pid,args= | awk 'BEGIN{status=1}{
name=$2
if(name !~ /^\[.*\]$/){sub(".*/","",name)} # strip dirname, if process name is not enclosed by square brackets.
if(name==cmd){status=0; if(q){exit}else{print $0}}
}END{exit status}' cmd="$1" q=$quiet
}
process='chromium-browser'
printf "Process \"${process}\" is "
if isProcessRunning -q "$process"
then printf "running.\n"
else printf "not running.\n"; fi
printf "Listing of matching processes (PID and process name with command line arguments):\n"
isProcessRunning "$process"
Here is my version. Features:
checks for exact program name (first argument of the function). search for "mysql" will not match running "mysqld"
searches program arguments (second argument of the function)
script:
#!/bin/bash
# $1 - cmd
# $2 - args
# return: 0 - no error, running; 1 - error, not running
function isRunning() {
for i in $(pidof $1); do
cat /proc/$i/cmdline | tr '\000' ' ' | grep -F -e "$2" 1>&2> /dev/null
if [ $? -eq 0 ]; then
return 0
fi
done
return 1
}
isRunning java "-Djava.util.logging.config.file=logging.properties"
if [ $? -ne 0 ]; then
echo "not running, starting..."
fi
[ $pid ] && [ -d /proc/$pid ] && command if you know the pid
The following shell function, being only based on POSIX standard commands and options should work on most (if not any) Unix and linux system. :
isPidRunning() {
cmd=`
PATH=\`getconf PATH\` export PATH
ps -e -o pid= -o comm= |
awk '$2 ~ "^.*/'"$1"'$" || $2 ~ "^'"$1"'$" {print $1,$2}'
`
[ -n "$cmd" ] &&
printf "%s is running\n%s\n\n" "$1" "$cmd" ||
printf "%s is not running\n\n" $1
[ -n "$cmd" ]
}
$ isPidRunning httpd
httpd is running
586 /usr/apache/bin/httpd
588 /usr/apache/bin/httpd
$ isPidRunning ksh
ksh is running
5230 ksh
$ isPidRunning bash
bash is not running
Note that it will choke when passed the dubious "0]" command name and will also fail to identify processes having an embedded space in their names.
Note too that the most upvoted and accepted solution demands non portable ps options and gratuitously uses a shell that is, despite its popularity, not guaranteed to be present on every Unix/Linux machine (bash)

Resources