1

I'm trying to write a for loop with grep. When grep returns a value I want to display the message "running". If no value is returned then display "available".

I think there is something is wrong with my if statement, but I can't find anything.

Any suggestions would be greatly appreciated.

    #!/bin/sh
    #JWR1.0, REL1.10

    echo "Content-type: text/html"
    echo ""

    chk_port = 'ps -ef | grep "port $i -"'

    for (( i=1; i<=5; i++ ))
    do
            if [[ $chk_port ]]; then
                    echo "Running - $i<br>"
            else
                    echo "Available - $i<br>"
            fi
    done

    echo "<br>"

    # For debugging


    ps -ef | grep "port 1 -"

Sample output:

    Available - 1
    Available - 2
    Available - 3
    Available - 4
    Available - 5

    apache 7706 7700 0 15:07 ? 00:00:00 grep port 1 -
4
  • Try replacing $chk_port with this: $(ps -ef | grep "port $i -") Commented Jul 22, 2013 at 22:27
  • @ed.: That makes the for-loop rather pointless, since it just checks five times to see if the process was originally running . . . Commented Jul 22, 2013 at 22:55
  • @ruakh: No - it evaluates $i each time in the loop now. Commented Jul 22, 2013 at 23:17
  • @ed.: Oh, I see; you're not suggesting to set chk_port to $(ps -ef | grep "port $i -"), you're suggesting to dispense with $chk_port and instead use $(ps -ef | grep "port $i -"). O.K., yes, good. :-) Commented Jul 22, 2013 at 23:20

1 Answer 1

1

I guess your problem is, there is no port $i in your ps's output, but your script thinks it exists.

The problem is, the command grep port $i - is also in ps -ef's output, it was clear in your debugging output. You can test it with ps -ef|grep foo

To avoid it, there is a trick, just do

chk_port=$(ps -ef | grep "[p]ort $i -")

for example:

kent$  ps -ef|grep nothing  
kent     10226  4752  0 00:36 pts/2    00:00:00 grep --color=auto nothing

kent$  ps -ef|grep [n]othing
zsh: no matches found: [n]othing

Also you could check the return code of grep (grep -q) to decide if the pattern was found. If no matches found, grep returns 1, otherwise 0.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.