Shell – Check for process and kill if running

processpsshell

I am trying to find if a process is running or not, and if it is runing then I want to call a script or print something. I tried with the below few ways, but it gives me syntax error or command not found error.

APP_ID = ps -eaf | grep -i `whoami` | grep -i <process_name> | grep -i java | awk '{print$2}'

if[''!= '${APP_ID}'] then
    echo "Stopping instance $APP_ID"

I get the result as below:

test.sh: line 15: APP_ID: command not found
test.sh: line 17: if[!= ${APP_ID}]: command not found
Stopping instance 

What is wrong in the above script? And if it has some errors, then why does it print the echo in the if condition?

Also the below script fails saying test.sh: line 3: [ps: command not found

if [ps -eaf | grep -i `whoami` | grep -i <process_name> | grep -i java]; then
    echo 'stop'
fi

Best Answer

Your syntax has many problems:

  • remove spaces around "=" when setting a variable

    wrong:

    APP_ID = value
    

    right:

    APP_ID=value
    
  • to run a program and put its output into a variable, you need $(...) (preferred in bash, not available in sh) or backticks `command` (supported in bash and sh). (and remember that when assigning a variable, quotes are not needed, but in other cases they are important: command "$(command)")

    wrong:

    APP_ID=command
    

    right:

    APP_ID=$(command)
    
  • add spaces around everything when using "[", and you need a semicolon or newline after the "]". This is because "[" is a bash builtin command, and the non-builtin one is also known as "test" (see man test), which just like other commands, takes its arguments separated by space:

    wrong:

    if[x!= y] then echo hello world fi
    

    right:

    if [ x != y ]; then echo hello world; fi
    
  • use double quotes, not single quotes when you want to expand a variable

    wrong:

    if [ '' != '${APP_ID}' ]; then
    

    right:

    if [ '' != "${APP_ID}" ]; then
    
  • Also for the above example, you can use -n (non-empty) instead of comparing to empty string

    if [ -n "${APP_ID}" ]; then
    
  • And for the ps example, you don't need grep and awk:

    APP_ID=$(ps -C whoami --no-header --format 'pid')
    

And so here is the fixed up script:

APP_ID=$(ps -C whoami --no-header --format 'pid')

if [ -n "${APP_ID}" ]; then
    echo "Stopping instance $APP_ID"
fi
Related Question