Home > Software design >  Bash | Script does not work in all directories. Why?
Bash | Script does not work in all directories. Why?

Time:05-04

The following script first tries to stop the tomcats (stored in array) in the normal way. If the Tomcats are still not stopped after 10 seconds, they will be forcibly killed.

The script works fine, but only in the directory it was created in. If I copy it to another folder then it doesn't work properly.

#!/bin/bash
            array=(
                    "service1-tomcat"
                    "service2-tomcat"
                    "service3-tomcat"
                    "service4-tomcat"
                    "service5-tomcat"
                    )    
            #Stopping
            if [ ! $(ps aux | grep [t]omcat/ | wc -l) -eq 0 ];then    
                    echo "STOP Tomcats"
                    for i in "${array[@]}"
                    do
                            /data/tomcats/$i/bin/shutdown.sh &> /tmp/output.txt
                    done
                    echo " done"    
            fi
            sleep 10
        
           #Killing
           if [ ! $(ps aux | grep [t]omcat/ | wc -l) -eq 0 ];then
            
                    echo "KILL $(ps aux | grep [t]omcat/ | wc -l) dogged Tomcats"
                    for i in "${array[@]}"
                            do
                                    if [ ! $(ps aux | grep $i | wc -l) -eq 0 ];then
                                            echo "$i"
                                    fi
                            done
            
                    kill -9 $(ps aux | grep [t]omcat | awk '{print $2}')
                    if [ $(ps aux | grep [t]omcat/ | wc -l) -eq 0 ];then
                             echo "done"
                    fi
            fi

The script was created in the /var/data/tomcats: If the script is executed here, following comes up, which does exactly what it is supposed to.

STOP Tomcats. 
 Done.
 KILL 1 dogged Tomcats
 service1-tomcat
 Done

however, when I run it in /var/data or in /tmp or whatever, it doesn't list the tomcats that need to be killed, but general ALL. The output looks like this:

STOP Tomcats. 
Done.
KILL 1 dogged Tomcats
service1-tomcat
service2-tomcat
service3-tomcat
service4-tomcat
service5-tomcat
Done

I can't explain why the script only works properly in one folder. There are no relative paths etc.

What am I doing wrong here?

CodePudding user response:

grep [t]omcat -- because the pattern is unquoted, the shell will treat it as a shell glob pattern. If there is a file named tomcat in the current directory, grep will get a plain "tomcat" regex pattern instead of the one with the brackets, and then the ps | grep pipeline may return too many results.

If you're sending a pattern to an external command (grep or tr are particularly common offenders), quote the pattern.


You might enjoy pgrep instead of ps | grep

  •  Tags:  
  • bash
  • Related