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:
right:
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:
right:
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:
right:
use double quotes, not single quotes when you want to expand a variable
wrong:
right:
Also for the above example, you can use -n (non-empty) instead of comparing to empty string
And for the ps example, you don't need grep and awk:
And so here is the fixed up script: