Monday, April 29, 2024
 Popular · Latest · Hot · Upcoming
9
rated 0 times [  9] [ 0]  / answers: 1 / hits: 1782  / 2 Years ago, tue, august 16, 2022, 10:50:24

I want to write script that accepts process name (I ask the user for process name each time followed by a prompt on the same line) if process exists it will print "EXISTS" or if it doesn't then "DOES NOT EXIST" depending on whether such a process is currently on the system.


Example:


Enter the name of process: bash
exists
Enter the name of process: bluesky
does not exist

My code:


#!/bin/bash
while true
do
read -p "Enter the name of process: "
if [ pidof -x > 0 ]; then
echo "exists"
else
echo "does not exist"
fi
done

The error message I receive.


pidof: unary operator expected

More From » bash

 Answers
1

There's a few things to correct here.


First, although you ask for user-input via read, you don't actually use the result anywhere. By default, read assigns what's read to a variable named REPLY so you'd want pidof -x "$REPLY"


Second, inside [ ... ] POSIX test brackets, > has its ordinary meaning as a redirection operator1. If you check your current directory, you will likely see it now contains a file named 0. The integer "greater than" test is -gt.


Third, your pidof -x inside the [ ... ] test is just a string; to execute it as a command and capture the result you need command substitution


[ "$(pidof -x "$REPLY")" -gt 0 ]

However, pidof may return multiple integers if multiple matching processes are found - which will cause yet another error. So I'd recommend instead using the exit status of pidof directly:


EXIT STATUS
0 At least one program was found with the requested name.

1 No program was found with the requested name.

So you could do


#!/bin/bash
while true
do
read -p "Enter the name of process: "
if pidof -qx "$REPLY"; then
echo "exists"
else
echo "does not exist"
fi
done



1 inside a bash [[ ... ]] extended test, > is a comparison operator - however it performs lexicographical rather than numerical comparison, so you'd still want -gt there. You could use > for integer comparison inside an arithmetic construct (( ... )) though.


[#527] Wednesday, August 17, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ameatoes

Total Points: 321
Total Questions: 106
Total Answers: 112

Location: Belarus
Member since Sat, Jul 18, 2020
4 Years ago
ameatoes questions
Fri, May 14, 21, 03:36, 3 Years ago
Sat, Oct 8, 22, 01:00, 2 Years ago
Fri, Feb 17, 23, 14:44, 1 Year ago
Sun, Oct 17, 21, 02:31, 3 Years ago
;