简体   繁体   中英

Can't grep command resultats in bash script

Good Morning,

Context : I would like to check every minute if a python script is running. In my cron, i call a script. The script's goal is to check if the process is running.

My script :

#!/bin/bash
DIR="path/to/directory"
CMD="python3 -u $DIR/script.py -arg1 $DIR/arg1 -arg2 $DIR/arg2 -arg3 $DIR/arg3"

if [ ! $(ps aux | grep 'my_pattern' | grep -v 'color')]
then
    echo "Success"
    "$CMD" > /dev/null
fi

With this script i want to grep the process and inverse the grep to exclude the color process. If the process is running, the command (ps aux | grep 'my_pattern' | grep -v 'color')returns me something if not, the command returns me nothing.

The error is ./script.sh: line 12: [!myuser+ : Untraceable command

The execution of the command did not returns me the result of the command but the process number of my command like if i did a ps aux of my command.

If it's not clear, please ask, difficult for me to translate the issue.

Thank you for answering.

EDIT : I HAVE APPLY the ocndition like this :

if [[ -z $(ps aux | grep 'my_pattern' | grep -v 'color') ]]

Now i don't have any errors but it never enter in my if condition.

With

if [[ -z $(ps aux | grep 'my_pattern' | grep -v 'color') ]]

(mind the typo as shown by klashxx)

you can check if the variable is empty.

So instead of using "!", i think it's more appropriate and effective to check if the grepping of ps aux is returning an empty string or not.

Let me know if this helped you or not.

EDITED: corrected '[' to '[['

EDITED AGAIN: for other users to know, if u need to check the existance of a process with this method append ! before -z flag to see if it is NOT empty

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM