Linux проверить наличие процесса

Bash script to check running process [duplicate]

I wrote a bash-script to check if a process is running. It doesn’t work since the ps command always returns exit code 1. When I run the ps command from the command-line, the $? is correctly set, but within the script it is always 1. Any idea?

#!/bin/bash SERVICE=$1 ps -a | grep -v grep | grep $1 > /dev/null result=$? echo "exit code: $" if [ "$" -eq "0" ] ; then echo "`date`: $SERVICE service running, everything is fine" else echo "`date`: $SERVICE is not running" fi 

Could you just check to see if you get non-empty output from the grep command instead of relying on return values?

I tried this and have a similar problem. The output is not taken into account. Here the code: #!/bin/bash SERVICE=$1 OUTPUT=$(ps -a | grep -v grep | grep $1) echo $OUTPUT if [ «$<#OUTPUT>» -gt 0 ] ; then echo » date : $SERVICE service running, everything is fine» else echo » date : $SERVICE is not running» fi

15 Answers 15

There are a few really simple methods:

pgrep procname && echo Running pgrep procname || echo Not running killall -q -0 procname && echo Running pidof procname && echo Running 

Your method will return a result even if a process just contains the process name you’re looking for. It’s not a solution to check with exact name.

This trick works for me. Hope this could help you. Let’s save the followings as checkRunningProcess.sh

#!/bin/bash ps_out=`ps -ef | grep $1 | grep -v 'grep' | grep -v $0` result=$(echo $ps_out | grep "$1") if [[ "$result" != "" ]];then echo "Running" else echo "Not Running" fi 

Make the checkRunningProcess.sh executable.And then use it.
Example to use.

20:10 $ checkRunningProcess.sh proxy.py Running 20:12 $ checkRunningProcess.sh abcdef Not Running 

this is what I needed to check if process running by it’s command line arguments as well. what is the difference ps aux vs ps -ef

I tried your version on BASH version 3.2.29, worked fine. However, you could do something like the above suggested, an example here:

#!/bin/sh SERVICE="$1" RESULT=`ps -ef | grep $1 | grep -v 'grep' | grep -v $0` result=$(echo $ps_out | grep "$1") if [[ "$result" != "" ]];then echo "Running" else echo "Not Running" fi 

I tried it out, doesn’t work neither. There must be something fishy with my environment (a shared hosting provider).

nothing special: the output is + SERVICE=rails + ps -a + grep -v grep + grep rails + result=1 + echo ‘exit code: 1’ exit code: 1 + ‘[‘ 1 -eq 0 ‘]’ ++ date + echo ‘Tue May 25 06:52:25 EDT 2010: rails is not running’

Just a heads up: ps -a only lists processes of the user in the current terminal. However, ps -A checks for ALL PROCESSES.

I use this one to check every 10 seconds process is running and start if not and allows multiple arguments:

#!/bin/sh PROCESS="$1" PROCANDARGS=$* while : do RESULT=`pgrep $` if [ "$" = null ]; then echo "$ not running, starting "$PROCANDARGS $PROCANDARGS & else echo "running" fi sleep 10 done 

Check if your scripts name doesn’t contain $SERVICE. If it does, it will be shown in ps results, causing script to always think that service is running. You can grep it against current filename like this:

#!/bin/sh SERVICE=$1 if ps ax | grep -v grep | grep -v $0 | grep $SERVICE > /dev/null then echo "$SERVICE service running, everything is fine" else echo "$SERVICE is not running" fi 

for those that want to use this as part of a script, and not as a function, change $0 to grep ps ax | grep -v grep | grep -v grep | grep $SERVICE > /dev/null

!/bin/bash CHECK=$0 SERVICE=$1 DATE=`date` OUTPUT=$(ps aux | grep -v grep | grep -v $CHECK |grep $1) echo $OUTPUT if [ "$" -gt 0 ] ; then echo "$DATE: $SERVICE service running, everything is fine" else echo "$DATE: $SERVICE is not running" fi

pgrep is a better solution, you still have the problem that you do not check the process name but the whole output of ps aux.

Читайте также:  Где докер хранит образы linux

Despite some success with the /dev/null approach in bash. When I pushed the solution to cron it failed. Checking the size of a returned command worked perfectly though. The ampersrand allows bash to exit.

#!/bin/bash SERVICE=/path/to/my/service result=$(ps ax|grep -v grep|grep $SERVICE) echo $ if $> 0 then echo " Working!" else echo "Not Working. Restarting" /usr/bin/xvfb-run -a /opt/python27/bin/python2.7 SERVICE & fi 
#!/bin/bash ps axho comm| grep $1 > /dev/null result=$? echo "exit code: $" if [ "$" -eq "0" ] ; then echo "`date`: $SERVICE service running, everything is fine" else echo "`date`: $SERVICE is not running" /etc/init.d/$1 restart fi

Those are helpful hints. I just needed to know if a service was running when I started the script, so I could leave the service in the same state when I left. I ended up using this:

 HTTPDSERVICE=$(ps -A | grep httpd | head -1) [ -z "$HTTPDSERVICE" ] && echo "No apache service running." 

I found the problem. ps -ae instead ps -a works.

I guess it has to do with my rights in the shared hosting environment. There’s apparently a difference between executing «ps -a» from the command line and executing it from within a bash-script.

A simple script version of one of Andor’s above suggestions:

!/bin/bash pgrep $1 && echo Running 

If the above script is called test.sh then, in order to test, type: test.sh NameOfProcessToCheck

I was wondering if it would be a good idea to have progressive attempts at a process, so you pass this func a process name func_terminate_process «firefox» and it tires things more nicely first, then moves on to kill.

# -- NICE: try to use killall to stop process(s) killall $ > /dev/null 2>&1 ;sleep 10 # -- if we do not see the process, just end the function pgrep $ > /dev/null 2>&1 || return # -- UGLY: Step trough every pid and use kill -9 on them individually for PID in $(pidof $) ;do echo "Terminating Process: [$], PID [$]" kill -9 $ ;sleep 10 # -- NASTY: If kill -9 fails, try SIGTERM on PID if ps -p $ > /dev/null ;then echo "$ is still running, forcefully terminating with SIGTERM" kill -SIGTERM $ ;sleep 10 fi done # -- If after all that, we still see the process, report that to the screen. pgrep $ > /dev/null 2>&1 && echo "Error, unable to terminate all or any of [$]" || echo "Terminate process [$] : SUCCESSFUL" 

I need to do this from time to time and end up hacking the command line until it works.

For example, here I want to see if I have any SSH connections, (the 8th column returned by «ps» is the running «path-to-procname» and is filtered by «awk»:

ps | awk -e '< print $8 >' | grep ssh | sed -e 's/.*\///g' 

Then I put it in a shell-script, («eval»-ing the command line inside of backticks), like this:

#!/bin/bash VNC_STRING=`ps | awk -e '< print $8 >' | grep vnc | sed -e 's/.*\///g'` if [ ! -z "$VNC_STRING" ]; then echo "The VNC STRING is not empty, therefore your process is running." fi 

The «sed» part trims the path to the exact token and might not be necessary for your needs.

Читайте также:  Share folder in linux mint

Here’s my example I used to get your answer. I wrote it to automatically create 2 SSH tunnels and launch a VNC client for each.

I run it from my Cygwin shell to do admin to my backend from my windows workstation, so I can jump to UNIX/LINUX-land with one command, (this also assumes the client rsa keys have already been «ssh-copy-id»-ed and are known to the remote host).

It’s idempotent in that each proc/command only fires when their $VAR eval’s to an empty string.

It appends » | wc -l» to store the number of running procs that match, (i.e., number of lines found), instead of proc-name for each $VAR to suit my needs. I keep the «echo» statements so I can re-run and diagnose the state of both connections.

#!/bin/bash SSH_COUNT=`eval ps | awk -e '< print $8 >' | grep ssh | sed -e 's/.*\///g' | wc -l` VNC_COUNT=`eval ps | awk -e '< print $8 >' | grep vnc | sed -e 's/.*\///g' | wc -l` if [ $SSH_COUNT = "2" ]; then echo "There are already 2 SSH tunnels." elif [ $SSH_COUNT = "1" ]; then echo "There is only 1 SSH tunnel." elif [ $SSH_COUNT = "0" ]; then echo "connecting 2 SSH tunnels." ssh -L 5901:localhost:5901 -f -l USER1 HOST1 sleep 10; ssh -L 5904:localhost:5904 -f -l USER2 HOST2 sleep 10; fi if [ $VNC_COUNT = "2" ]; then echo "There are already 2 VNC sessions." elif [ $VNC_COUNT = "1" ]; then echo "There is only 1 VNC session." elif [ $VNC_COUNT = "0" ]; then echo "launching 2 vnc sessions." vncviewer.exe localhost:1 & vncviewer.exe localhost:4 & fi 

This is very perl-like to me and possibly more unix utils than true shell scripting. I know there are lots of «MAGIC» numbers and cheezy hard-coded values but it works, (I think I’m also in poor taste for using so much UPPERCASE too). Flexibility can be added with some cmd-line args to make this more versatile but I wanted to share what worked for me. Please improve and share. Cheers.

Источник

Bash script — проверка программы на запущенность и ее запуск

В общем, мне нужно было как-то примитивно проверить запущена ли программа, а если нет, то запустить её. Да, есть программы для мониторинга всего этого дела (например, mon), но ставить их из-за одной программы не хотелось, поэтому написал небольшой скрипт.

#!/bin/bash ret=$(ps aux | grep [h]top | wc -l) if [ "$ret" -eq 0 ] then < echo "Running Htop" #output text sleep 1 #delay htop #command for run program exit 1 >else < echo "EXIT. Htop already running!" exit 1 >fi;

Для начала смотрим запущена программа или нет:

ps aux выводит запущенные процессы.
grep [h]top выводит результаты с htop, при этом если первую букву процесса взять в квадратные скобки, то ‘grep htop’ будет исключаться из списка.
wc -l подсчитывает количество строк (запущенных процессов).
Выглядит это так:

total@total-MS-7638:~$ ps aux USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.1 86904 4460 ? Ss 16:04 0:00 /sbin/init root 2 0.0 0.0 0 0 ? S 16:04 0:00 [kthreadd] root 3 0.0 0.0 0 0 ? S 16:04 0:00 [ksoftirqd/0] root 5 0.0 0.0 0 0 ? S< 16:04 0:00 [kworker/0:0H] root 6 0.0 0.0 0 0 ? S 16:04 0:00 [kworker/u:0] root 7 0.0 0.0 0 0 ? S< 16:04 0:00 [kworker/u:0H] root 8 0.0 0.0 0 0 ? S 16:04 0:00 [migration/0] root 9 0.0 0.0 0 0 ? S 16:04 0:00 [rcu_bh] syslog 1031 0.0 0.0 241120 1824 ? Sl 16:04 0:00 rsyslogd -c5 root 1045 0.0 0.0 83408 3280 ? Ss 16:04 0:00 /usr/sbin/modem-manager root 1047 0.0 0.0 19240 1792 ? Ss 16:04 0:00 /usr/sbin/bluetoothd root 1076 0.0 0.0 0 0 ? S< 16:04 0:00 [krfcommd] root 1149 0.0 0.2 179000 9384 ? Ss 16:04 0:00 /usr/sbin/cupsd -F root 1163 0.0 0.1 246044 5868 ? Ssl 16:04 0:00 NetworkManager root 1168 0.0 0.1 250220 6872 ? Sl 16:04 0:00 /usr/lib/policykit-1/polkitd --no-debug root 1170 0.0 0.0 10720 916 tty4 Ss+ 16:04 0:00 /sbin/getty -8 38400 tty4 root 1176 0.0 0.0 10720 920 tty5 Ss+ 16:04 0:00 /sbin/getty -8 38400 tty5 root 1182 0.0 0.0 10720 908 tty2 Ss+ 16:04 0:00 /sbin/getty -8 38400 tty2 root 1184 0.0 0.0 10720 916 tty3 Ss+ 16:04 0:00 /sbin/getty -8 38400 tty3 root 1186 0.0 0.0 10720 916 tty6 Ss+ 16:04 0:00 /sbin/getty -8 38400 tty6 root 1189 0.0 0.1 47312 4404 ? Ssl 16:04 0:01 /opt/teamviewer8/tv_bin/teamviewerd -f root 1214 0.0 0.0 4508 828 ? Ss 16:04 0:00 acpid -c /etc/acpi/events -s /var/run/acpid.socket daemon 1222 0.0 0.0 12792 136 ? Ss 16:04 0:00 atd root 1224 0.0 0.0 14992 980 ? Ss 16:04 0:00 cron root 1225 0.0 0.0 19148 728 ? Ss 16:04 0:00 /usr/sbin/irqbalance whoopsie 1234 0.0 0.1 282716 5044 ? Ssl 16:04 0:00 whoopsie openldap 1237 0.0 0.1 375504 6300 ? Ssl 16:04 0:00 /usr/sbin/slapd -h ldap:/// ldapi:/// -g openldap -u openldap -F colord 1266 0.0 0.1 210224 5444 ? Sl 16:04 0:00 /usr/lib/colord/colord root 1267 0.0 0.0 11876 840 ? Sl 16:04 0:00 /usr/sbin/pcscd root 1283 0.0 0.0 113448 1512 ? Ss 16:04 0:00 /usr/sbin/sensord -f daemon root 1296 0.0 0.0 124300 1948 ? S 16:04 0:00 smbd -F root 1311 0.0 0.0 0 0 ? S< 16:04 0:00 [iprt] root 1356 0.0 0.0 269148 3328 ? Ssl 16:04 0:00 lightdm root 1378 4.2 1.5 194792 60556 tty7 Ss+ 16:04 9:01 /usr/bin/X :0 -core -auth /var/run/lightdm/root/:0 -nolisten tcp total 3893 1.8 0.0 20752 2120 pts/1 S+ 19:35 0:00 htop total 3897 1.5 0.0 17496 3628 pts/2 Ss 19:35 0:00 bash total 3945 0.0 0.0 13352 1256 pts/2 R+ 19:35 0:00 ps aux total@total-MS-7638:~$ ps aux | grep htop total 3893 1.8 0.0 20752 2120 pts/1 S+ 19:35 0:00 htop total 3947 0.0 0.0 10684 952 pts/2 S+ 19:35 0:00 grep --color=auto htop total@total-MS-7638:~$ ps aux | grep [h]top total 3893 1.8 0.0 20752 2120 pts/1 S+ 19:35 0:00 htop total@total-MS-7638:~$ ps aux | grep [h]top | wc -l 1 total@total-MS-7638:~$ ps aux | grep htop | wc -l 2 total@total-MS-7638:~$

После этого нужно написать условие проверки и запуска программы.
if [ "$ret" -eq 0 ] - если ( if ) значение переменной (ключ -eq означает равно) равно 0, то ( then ):
echo "Running Htop" - выводим текст: "Запускается Htop";
sleep 1 - ставим задержку при запуске в 1 секунду;
htop - запускаем программу Htop;
exit 1 - выходим из скрипта;
Иначе ( else ):
echo "EXIT. Htop already running!" - выводим текст: "Htop уже запущен!"
exit 1 - выходим из скрипта.
Конструкция "Если. то. иначе. " обязательно заканчивается fi ;

Читайте также:  Открыть менеджер файлов linux

Писать на Bash несложно, а также весьма увлекательно, в прочем, как и все в программировании. Так что попробуйте сами что-нибудь написать, у вас обязательно получится. Тем более, что по bash полно всякой документации, в том числе и на русском языке.

32 комментария к записи “ Bash script — проверка программы на запущенность и ее запуск ”

if [ "$ret" -eq 1 ] вот так работает с нулем всегда считает запущенным так как сама команда греп создает процесс и таким именем

Источник

Оцените статью
Adblock
detector