A Linux tomcat automatic deployment shell script

Posted by ifubad on Sun, 19 Dec 2021 05:39:51 +0100

A Linux tomcat automatic deployment shell script

Because Jenkins was installed on the server to realize automatic deployment failed, we found an alternative method and copied an automatic deployment script on the Internet. This script is written in shell language, and I have never been in contact with shell programming before, so I try to disassemble this script sentence by sentence to get a glimpse of the leopard.

#! /bin/sh
echo '####################Start automatic deployment####################'
path=$(pwd) #current path
backupTime=$(date +'%Y%m%d_%H_%M_%S')
tomcatPath=/home/dev/apache-tomcat-8.5.42/ #Specify the tomcat file directory name
cd $tomcatPath/bin || exit #Enter the bin directory of tomcat
PID=$(ps -fu root|grep tomcat|grep -v grep|awk '{print $2}') # scene
if [ -z "$PID" ];then
 echo "no tomcat process"
else
 echo "Start safe end process"
 kill -15 "$PID"
# ./shutdown.sh #Stop tomcat service
sleep 5
  if [ -z "$PID" ];then
    echo 'process'"$PID"'Has ended safely'
  else
    echo 'The process did not end safely. Start forced end'
    kill -9 "$PID"
    echo 'process'"$PID"'Has ended'
  fi
fi
sleep 1 #Sleep for 1s
cd ../webapps || exit #Enter the webapps directory of tomcat
rm -fr helloWorld #Delete helloWorld file directory
echo 'File directory deletion complete'
mv helloWorld.war ./backup/helloWorld.war."$backupTime" #Backup to backup
echo 'Backup complete'
sleep 1 #Sleep for 1s
cp "$path"/helloWorld.war ./ #Copy war to webapps path
sleep 1 #Sleep for 1s
cd ../bin || exit
./startup.sh #Start tomcat service
echo '####################End of deployment####################'

The script is simple, only 30 lines in total. At runtime, first modify the permissions of the file to executable: chmod +x comdfile, and set the file format to Unix.

  1.    #! /bin/sh
    

    Shell programming takes # as the annotation, but for #/ bin/sh is not. "#! / bin/sh" is a declaration of the shell, which type of shell is used and where its path is. (#! / bin/sh means that the script uses / bin/sh to interpret and execute, #! Is a special indicator, followed by the path of the shell that interprets the script. Of course, the path is not the only one.)

  2. echo '####################Start automatic deployment####################'
    

    echo command is used to output text to the window, which is equivalent to system. Net in Java out. Println (), nothing to say.

  3.    path=$(pwd) #current path
    

    Pwd is a command in Linux that can be used to view the full path of the current working directory. In short, there will be a current working directory when the terminal operates. When the current location is uncertain, pwd is used to determine the exact location of the current directory in the file system. Assign the path referred to by PWD to the path variable. After switching directories later, the value of path will not change.

  4.    backupTime=$(date +%Y%m%d_%H_%M_%S)
    

    Method of formatting date in shell

    1) Display system time

    1. date CST Central Standard Time - Mon Aug 23 10:52:19 CST 2021
    2. date -R time with time zone - Mon, 23 Aug 2021 10:52:37 +0800

    2) Format date

    ​ $(date +'%Y-%m-%d %H:%M')-2021-08-21 10:51

    Back 2 days ago:
    $(date -d '2 day ago' '+%Y/%m/%d %H:%M:%S')-2021/08/21 10:51:01

    See details Usage of Linux date command (transfer) - asxe - blog Garden (cnblogs.com)

  5.   tomcatPath=/home/dev/apache-tomcat-8.5.42 #Specify the tomcat file directory name
    

    Similar to string a = "Hello world"; There's nothing to say.

  6.    cd $tomcatPath/bin || exit #Enter the bin directory of tomcat
    

    cd is a basic command of Linux. It is used to switch directories. If it fails, exit the script. There's nothing to say.

    $means that variables are followed. The combination of the two is / home / dev / apache-tomcat-8.5 42 / bin.

  7.   PID=$(ps -fu root|grep tomcat|grep -v grep|awk '{print $2}')
    

    Disassemble layer by layer. The whole means to assign a value to the PID variable, $(...) Well, the whole in parentheses is treated as a variable.

    Then ps -fu root|grep tomcat|grep -v grep|awk '{print }}' in parentheses.

    First of all, | is the pipe symbol, which functions as its name. The result of the command on the left of the pipe is used as the basis of the command on the right.

    ps is a Linux command that displays a process. ps EF and ps Fu are commonly used

    ps -ef

    -A  Show all programs.
    -e  When programs are listed, the environment variables used by each program are displayed, and the effect is the same as-A identical
    -f  display UID,PPIP,C And STIME Field, with ASCII Character display tree structure to express the relationship between programs.
    -u	 Display program status in a user dominated format.
    

    In the shell command, grep command is a search command for text lines.

    In the figure above, ps -ef|grep helloWorld obviously does not have such a program. However, since the command itself belongs to a process, it will find out itself.

    There is a segment in the pipeline connection that is | grep -v grep| - v can filter out the process lines containing grep, leaving only the target content.

    ps -fu root

    Since this command contains - u, the user id to be searched can be carried.


    awk '{print }}' is the last segment of the pipeline connection, where awk is the text analysis language of Linux. This command is simply to read the pipeline processing results line by line, print the second field with a space as a separator. The second field just found is the PID of this process.

  8. if [ -z "$PID" ];then
     echo "no tomcat process"
    else
     kill -15 "$PID"
    # ./shutdown.sh #Stop tomcat service
    sleep 2
      if [ -z "$PID" ];then
        echo 'process'"$PID"'Has ended safely'
      else
        echo 'The process did not end safely. Start forced end'
        kill -9 "$PID"
        echo 'process'"$PID"'Has ended'
      fi
    fi
    

    Look at this piece together, if then ... FI is a structured command for shell scripts. Grammatical formats are divided into

    • if command;then command;fi (if the condition is met, then execute the command after then)

    • if command ... then ...else...fi (if the condition is met, then execute the command after then, otherwise execute the command after else)

    • if command ...then ...elif...then... Multi layer elif Fi (if the if judgment conditions are met, execute the command action after then; if the elif judgment conditions are met, execute the elif judgment conditions)

    It should be noted that in the judgment condition of if, double brackets are used for numerical operation, and double brackets are used for string comparison.

    #!/bin/bash
    # Double parentheses for numerical operations
    num1=10
    if (( $num1 + 10 > 20 ))
    then
        echo "1"
    else
        echo "2"
    fi
    
    # Use parentheses to compare strings
    if [[ `ymx` != "root" ]]
    then
            echo "ymx"
    fi
    

    Compare character writing:

    # Compare character writing:
    -eq # be equal to
    -ne # Not equal to
    -gt # greater than
    -lt # less than
    -le # Less than or equal to
    -ge # Greater than or equal to
    -z  # Empty string
     =  # Two characters are equal
    !=  # Two characters are not equal
    -n  # Non empty string
    # give an example:
    if [ $# -ge 2 ];then
    echo "You provided too many parameters!"
    exit 1
    else
     if [ $# -ne 0 ];then
      if [ $1 = s ];then
      echo "on e"
      else
      echo "two"
      fi
     else
     echo "3"
     fi
    fi
    

    In the above example, another $#, which is a special variable in the shell, appears.

    Special variable $0 $1 $2 $? $# $@ $*, These variables can be used as global variables in scripts.

    nameexplain
    $0Script name
    $1-9Parameters 1 to 9 during script execution
    $?Return value of script
    $#The number of parameters entered during script execution
    $@Specific contents of the input parameters (take the input parameters as one or more objects, that is, a list of all parameters)
    $*The specific content of the input parameter (take the input parameter as a word)

    Also note the difference between single quotation marks, double quotation marks and no quotation marks.

    • Single quotation mark

      It can be said that what you see is what you get: that is, the contents in single quotation marks are output as they are, or what you see in single quotation marks will be output.

    • Double quotation mark

      Output the contents in double quotation marks;

      If there are commands and variables in the content, the variables and commands will be parsed out first, and then the final content will be output. The command or variable in double quotation marks is written as ` command or variable 'or $(command or variable).

    • No quotation marks

      If the content is output, the string containing spaces may not be regarded as an overall output;

      If there are commands and variables in the content, the variables and commands will be parsed first, and then the final content will be output;

      If the string contains special characters such as spaces, it cannot be completely output, and double quotation marks need to be added. Generally, continuous strings, numbers, paths, etc. can be used, but it is best to replace them all with double quotation marks.

    Finally, looking back at this sentence, it is very clear: if the "variable PID" is empty and true, the statement of "no tomcat process" will be output; Otherwise, execute shutdown. In the current directory SH, the end command of tomcat.

  9.     kill -9 $PID
    

    The kill command is a linux kill process command.

    Usage: kill [-s signal declaration | - n signal number | - signal declaration] process number | task declaration Or kill -l [signal declaration]

    Here - 9 is the - n signal number. When - * is not transmitted, the default value is - 15.

    [external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-wlicmt6f-1629691931844)( https://i.loli.net/2021/08/20/DnEXFTYpq5jARve.png )]

    To give an inappropriate analogy, -15 it's like the Emperor gave his courtiers a death sentence, and the courtiers can also write a suicide note to take care of the afterlife;
    -It's like killing in court without giving any chance to respond.

    See: Linux kill, kill-15, kill-9 differences

  10. sleep 5 #Sleep for 5s
    

    For the hibernation command, one thing you can pay attention to is that when it does not mark the unit, it defaults to the unit of seconds, and it can also mark the units of S, m and h; There's nothing else to say.

  11.    rm -fr helloWorld #Delete helloWorld file directory
    

    The rm command is a delete command,

    Parameter - r can delete all files and directories in the directory;

    -f can delete read-only files without confirming commands one by one.

  12.  mv helloWorld.war ./backup/helloWorld.war."$backupTime" #Backup to backup
    
     cp "$path"/helloWorld.war ./ #Copy war to webapps path
    

    The mv command moves the old war package to the backup directory under the same level directory, and adds a time variable after the file name for backup.

    The cp command copies the new war package in the initial script running directory to the current directory.

  13. cd ../bin || exit
    ./startup.sh #Start tomcat service
    

    Switch to the bin directory and execute the startup script of tomcat.

This completes the execution of the script.

Topics: Linux shell