SoFunction
Updated on 2025-03-02

Shell scripts realize real-time detection of file changes

Using python for web development, it is now popular to use uwsgi to call python programs. However, after using uwsgi for a while, I found that there is a disadvantage that uwsgi must be restarted after each source code to take effect, including changing the template file. I am a lazy person, and after a period of repeated changes - after restarting, I finally couldn't stand it. I decided to write a script to time the file changes in the program directory and restart uwsgi in time to free my hands and ignore these trivial restart work. I spent some time writing a script to determine whether to change, and then determine whether uwsgi needs to be restarted.

The script content is released below:

#!/bin/bash
# Author   : cold
# Filename  : 
# Useage   : sh  [dir]
checkisdir()
    # Have one argument
    # The argument is a directory
    for i in `ls $1 | sed -e 's/ /\n/g'`
    do
        if [ -d $1/$i ]
        then
            if [ $i == "bin" -o $i == "lib" -o $i == "include" ]  # Directory that you don't want to detect (here is the environment file generated using virtualenv)            then
                continue
            fi
            dir="$1/$i"
            checkisdir $dir
        else
            files=$files'\n'$1'/'$i
        fi
    done
    echo -e $files
}
while true
do
    if [ -e /tmp/ ]
    then
        for i in `checkisdir $1`
        do
            if [ -e /tmp/ ]
            then
                stat $i | grep Change > /tmp/
                rm -f /tmp/
                continue
            fi
            stat $i | grep Change >> /tmp/
        done
        diff /tmp/ /tmp/ > /tmp/
        if [ $? -eq 0 ]
        then
            sleep 10
        else
            /etc// restart          # Change this to what you want to do            patch /tmp/ /tmp/
        fi
    else
        for i in `checkisdir $1`
        do
            stat $i | grep Change >> /tmp/
        done
        continue
    fi
done

Here we mainly test to restart uwsgi after the change. How to use: My bottle program is under /code/python:

Copy the codeThe code is as follows:

sh /code/python &

If you use svn, you can refer to the following code:

#!/bin/bash
# Author    : cold
# Filename   : 
# Describle   : To Check update of svn

while true
do
    cd /code/python
    svn up | grep At > /dev/null 2>&1
    if [ $? -eq 0 ]
    then
        sleep 30
    fi

    svn up | grep Updated > /dev/null 2>&1
    if [ $? -eq 0 ]
    then
        /etc// restart
    fi
done