How to check if a process id (pid) exists
You have two ways:
Lets start by looking for a specific application in my laptop:
[root@pinky:~]# ps fax | grep mozilla 3358 ? S 0:00 _ /bin/sh /usr/lib/firefox-3.5/run-mozilla.sh /usr/lib/firefox-3.5/firefox
16198 pts/2 S 0:00 _ grep mozillaAll examples now will look for PID 3358.
First way: Run “ps aux” and grep for the PID in the second column. In this example I look for firefox, and then for it’s PID:
[root@pinky:~]# ps aux | awk '{print $2 }' | grep 3358
3358So your code will be:
if [ ps aux | awk '{print $2 }' | grep -q $PID 2> /dev/null ]; then kill $PID
fiSecond way: Just look for something in the /proc/$PID directory. I am using “exe” in this example, but you can use anything else.
[root@pinky:~]# ls -l /proc/3358/exe
lrwxrwxrwx. 1 elcuco elcuco 0 2021-06-15 12:33 /proc/3358/exe -> /bin/bashSo your code will be:
if [ -f /proc/$PID/exe ]; then kill $PID
fiBTW: whats wrong with kill -9 $PID || true ?
EDIT:
After thinking about it for a few months.. (about 24…) the original idea I gave here is a nice hack, but highly unportable. While it teaches a few implementation details of Linux, it will fail to work on Mac, Solaris or *BSD. It may even fail on future Linux kernels. Please – use “ps” as described in other responses.
How to test if a process exists in bash?
I want to make sure node is running when logging in. So in my .bashrc file I have:
pkill node
sleep 1
node server.js &Of course, that doesn’t check if node is running… it simply kills it and starts it up again. Instead I’d like something like this:
node_process = $(pidof node)
if [not_exists node_process]; then node server.js &
fiThe problem is the not_exists method doesn’t seem to exist :). How do I test the existence of a number or string in Bash and is this the best way to ensure node is up and running upon login?
How to verify if a file exists in a batch file?
Here is a good example on how to do a command if a file does or does not exist:
if exist C:myprogramsyncdata.handler echo Now Exiting && Exit
if not exist C:myprogramhtmldata.sql ExitWe will take those three files and put it in a temporary place. After deleting the folder, it will restore those three files.
xcopy "test" "C:temp"
xcopy "test2" "C:temp"
del C:myprogramsync
xcopy "C:temp" "test"
xcopy "C:temp" "test2"
del "c:temp"Use the XCOPY command:
xcopy "C:myprogramhtmldata.sql" /c /d /h /e /i /y "C:myprogramsync"I will explain what the /c /d /h /e /i /y means:
/C Continues copying even if errors occur. /D:m-d-y Copies files changed on or after the specified date. If no date is given, copies only those files whose source time is newer than the destination time. /H Copies hidden and system files also. /E Copies directories and subdirectories, including empty ones. Same as /S /E. May be used to modify /T. /T Creates directory structure, but does not copy files. Does not include empty directories or subdirectories. /T /E includes /I If destination does not exist and copying more than one file, assumes that destination must be a directory. /Y Suppresses prompting to confirm you want to overwrite an existing destination file.
`To see all the commands type`xcopy /? in cmdCall other batch file with option sync.bat myprogram.ini.
I am not sure what you mean by this, but if you just want to open both of these files you just put the path of the file like
Path/sync.bat
Path/myprogram.iniIf it was in the Bash environment it was easy for me, but I do not
know how to test if a file or folder exists and if it is a file or
folder.
You are using a batch file. You mentioned earlier you have to create a .bat file to use this:
I have to create a .BAT file that does this:
If not exists then exit cmd
exit is a key word in DOS/Command Prompt – that’s why goto exit
doesn’t work.
Using if not exist “file name” exit dumps you out of that batch file.
That’s fine if exiting the batch file is what you want.
If you want to execute some other instructions before you exit, change the label to something like :notfound then you can goto notfound
and execute some other instructions before you exit.
(this is just a clarification to one of the examples)
Оператор if командная строка
if условие (оператор1) [else (оператор2)]
Вначале идет проверка условия, если оно выполняется, идет переход к выполнению оператора1, если нет – к оператору2. Если после ключевого слова if прописать not (if not), то: произойдет проверка условия, если оно не выполниться – переход к оператору1, если условие выполняется – переход к оператору2.
Давайте откроем редактор notepad и пропишем в нем такой код:
Как я уже сказал, мы можем использовать не один оператор (командной строки) cmd if, а несколько, посмотрите на данный пример:
Тут, как и прежде идет проверка передаваемого сценарию параметра, если значение равно 1, то произойдет последовательное выполнение трех команд:
Для последовательного выполнения команд мы использовали знак конкатенации (объединения) “&”. При невыполнении условия произойдет вызов утилиты netstat.
Что бы проверить существование переменной, используются операторы if defined (если переменная существует) и if not defined (если переменная не существует):
Если вы запустите на выполнение данный код, то в окне командной строки будут выведены две строки:
100NOT EXIST!!! Var1
Вначале, в сценарии происходит создание переменной Var1 и присвоение ей значения 100, далее идет проверка: если переменная Var1 существует, вывести ее значение. Потом мы удаляем переменную и снова запускаем проверку: если переменная Var1 не существует, вывести строку NOT EXIST!!! Var1.
Мы вправе использовать условный оператор if как вложенный:
В данном примере, первый оператор командной строки if проверяет, равен ли первый аргумент 1, если да, то идет выполнение второго условно оператора и проверка на значение другого аргумента.
Обратите внимание!!! Все переменные определяются как строки. При проверке условия я заключал имена переменных и значений в двойные кавычки, это позволяет избежать ошибок, так как параметры или аргументы могут содержать пробелы, или же у переменной может и вовсе отсутствовать значение.
Давайте теперь посмотрим на такой пример:
Тут идет проверка первого аргумента, и регистр строки учитывается, что бы отключить учет регистра при проверке строк, после оператора if нужно прописать ключ /I:
В данном случае, передадим мы строку SLOVO, slovo, SloVo и так далее, все ровно на экран консоли выведется строка “slovo”, так как учет регистра знаков будет отключен.
Оператор if командная строка, операторы сравнения
Кроме оператора сравнения “==” можно использовать и другие операторы для проверки условия:
- equ «Равно». Дает True, если значения равны
- neq «Не равно». Дает True, если значения не равны
- lss «Меньше». Дает True, если зпачение1 меньше, чем значение2
- lcq «Меньше или равно». Дает True, если значепие1 равно или меньше, чемзначение2
- gtr «Больше». Дает True, если значение1 больше, чем значение2
- geq «Больше или равно». Дает True, если значепие1 равно или больше, чем значение2
В этой статье мы рассмотрели условный оператор командной строки if.




