Ubuntu – How to compare any string from output through shell script of unix command

bashcommand linescripts

I get a log file as soon as I run one command(process is still running in background). Now I want to fetch the status (clean or un-clean) from that log file. If status is clean then I will leave the process as is else, if it is un-clean then I have to kill the process which was started by my first command and re-run the same command again.

I have tried with cat logfilename | grep "un-clean". But I don't know how to verify this output in shell script.

I want something like (roughly) var= clean then the output of above command == var if yes then echo "ok" else re-run command

I have tried some of the commands but not working for me.

Best Answer

Basically, you want this structure

if grep -q "un-clean"  /path/to/log_file.log ;
then
    # put some command in case we find result is unclean
else 
    # if the output is ok, do something else
fi

All it does is to silently (without printing to screen) check if there is a match of string "unclean" in the file . If there is we do the if part, otherwise - we do else part.

Here's an example:

$> if grep -q 'root' /etc/passwd ; then  echo "This user exists" ; else echo "This user doesn't exist"; fi    
This user exists
$> if grep -q 'NOEXIST' /etc/passwd ; then  echo "This user exists" ; else echo "This user doesn't exist"; fi 
This user doesn't exist

What also can be done is to start command you want from script, but in background. That way we can have it's PID. Here's what I mean

$> echo "HelloWorld"   &                                                                                      
[1] 6876

Adding & causes echo "HelloWorld" run in background, and we have it's PID stored in $! variable. Thus, we can do something like,

some-command  &
CMD_PID=$!
if grep -q "un-clean"  /path/to/log_file.log ;
then
         kill -TERM $CMD_PID
else 
        # if the output is ok, do something else
fi