0
func () {    
    local arrayOfParams=$@
    local CMD="ps aux | grep -v grep"
    
    for item in ${arrayOfParams[@]};
    do
        local CMD="$CMD | grep -e $item"
    done
    
    echo "Current process PID : $$"
    
    echo "`date`: CMD is -> $CMD"
    local isProcRunning=`eval ${CMD}`
    if [[ 0 -eq `echo "$isProcRunning" | wc -l` ]];
    then
        echo "`date`: Following process is running: "
        echo "$isProcRunning"
        echo ""
        if [[ "$FORCE_RUN" == true ]];
        then
            echo "`date`: User forced the run of current process ..."
            # we extract the PIDs of proces mathcing our search criteria
            PIDS=(`echo $isProcRunning | awk '{print \$2}'`)
            for PID in "${PIDS[@]}";
            do
                # we extract the command running on said PID so that we know what we kill
                local PIDCMD=`ps -o cmd -p ${PID} --no-headers`
                echo "`date`: Killing PID: $PID with CMD -> $PIDCMD"
                kill -9 $PID
            done
            
        else
            echo "`date`: Current process will exit!!!"
        fi
        
        exit 0
    fi
}

The above code is meant to check if current process is already running .

I use ps -ef and grep based on some params which should be found under CMD

I remove the line coresponding to the current PID and then I expect the wc -l to return 0, but it's returning 1.

I run that line outside of the script and I get 0 indeed.

Any idea why this is happening ?

Barmar
  • 741,623
  • 53
  • 500
  • 612
user91991993
  • 705
  • 5
  • 11
  • Do you have the `pgrep` command available to you? That will be much better than your ad hoc grep code. – Barmar Nov 23 '22 at 21:02
  • no answer; just some basic debuging suggestions ... add `set -x` (enable debug mode) at the top of the function (add `set +x` - disable debug mode - at the end of the function) ... add `typeset -p ` after a variable/array is populated (so you can see the actual contents) ... run the function and review the debug output to where the issue lies – markp-fuso Nov 23 '22 at 21:08
  • The immediate problem is that `echo` will always output at least one line, even if it's blank. To test whether a string is empty, use `if [[ -z "$isProcRunning" ]]`. There are a number of other fragile/dubious/generally bad practices here. [shellcheck.net](https://www.shellcheck.net) will point out some of them. Also, building commands as strings and using `eval` tends to produce bugs. And do you really want to search for processes that match *all* arguments, or *any* argument? That is, should `func foo bar` find "foo", "bar", and "foobar", or should it *only* find "foobar"? – Gordon Davisson Nov 23 '22 at 22:35
  • @Barmar pgrep is not available – user91991993 Nov 24 '22 at 09:19
  • @GordonDavisson thanks for the tips. this solved my problem and shellcheck.net is a very useful tool. – user91991993 Nov 24 '22 at 09:20

0 Answers0