0

my code is the following

#!/bin/bash

function execute_php () {

process=$(ps -A | grep php)
if [-z "$process"]; then echo "no php running" fi

}

(sleep 5 && execute_php)

I am trying to determine if the command "php" is being executed, but I get the error "line 8: syntax error near unexpected token `}'"

I am a newbie with bash scripting, and even though I searched for the error, I couldn't find it.

0

1 Answer 1

2

if [-z "$process"]

needs to have spaces:

if [ -z "$process" ]

This is almost certainly duplicated in at least 1000 different questions, but the short of it is that you are trying to invoke a command named [, but you are accidentally invoking a command named [-z which probably doesn't exist in your PATH. [ is not part of the grammar. It is a command. This would be more clear if you instead write:

if test -z "$process"

Also, you're missing a semi-colon (or a newline) before fi.

Note further that you can more easily check the status of grep by just checking it directly:

execute_php () {
    if ! ps -A | grep -q php; then echo "no php running"; fi
}

And further note that this would probably be better if it returned non-zero if the desired process is not running:

execute_php() { 
    if ! ps -A | grep -q php; then echo "no php running" >&2; return 1; fi
}

But, honestly that's too verbose (and the name of the function seems wrong. You're not executing anything.) IMO, you should just write:

check_php() {
    ps -A | grep -q php
}

and then callers can do if check_php; then ....

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

1 Comment

Thanks god people like you exists in this world

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.