Oscar Jofre
Oscar Jofre

Reputation: 143

linux script to move files in directories with data

I'm using freeradius with daloradius appliance. Now there are lots of routers connected to this radius server and the database and log files are growing too much.

The log files from freeradius are saved on:

/radacct/xxx.xxx.xxx.xxx/detail-20150404

xxx.xxx.xxx.xxx are differents IP clients, so there are lots of folders and lots of files inside these folders.

I can add this directory to rotate log because the file detail-TODAY can't be modified during the day and can be accessible all the 24h.

So I'm asking for:

A script to move /radacct/xxx.xxx.xxx.xxx/detail-yyyymmdd to a new folder /radacct_old/xxx.xxx.xxx.xxx/detail-yyyymmdd.

We have to move all files except where yyyymmdd is the current date (date when the script is executed). After this I can rotate log radacct_old or just add to zip radacct_old_yyyymmdd.

I'm planning to do this job every week or so.

What’s the best way do you suggest?

Upvotes: 1

Views: 667

Answers (1)

ShellFish
ShellFish

Reputation: 4551

Try something like this:

function move {
    today=$(date +%Y%m%d)
    file="${1#/radacct/}"
    ip="${file%%/*}"
    name="${file##*/}"
    if [[ ! $name =~ detail-$today ]]; then
        dir="/radacct_old/$ip"
        [ -d "${dir}" ] || mkdir "${dir}"            
        mv "${1}" "${dir}/${name}"
    fi
}
export -f move

find /radacct -type d -mindepth 2 -maxdepth 2 -name '*detail*' -exec bash -c 'move "$0"' {} \;

Beware this is untested, you will certainly be able to fill the gaps. I will test it out and debug later if you can't seem to make it work. Post when you have further questions.

Explanation: generally the script looks for all directories of the required format and moves them (last two lines) by calling a function (beginning).

Move function

  • today=$(date +%Y%m%d) constructs the date in the required format.
  • file="${1#/radacct/}" remove leading directory name from the directory we found using find.
  • ip="${file%%/*}" extract the ip address.
  • name="${file##*/}" extract the dir name.
  • if [[ ! $name =~ detail-$today ]]; then if dir name is from today.
  • dir="/radacct_old/$ip" construct target directory.
  • [ -d "${dir}" ] || mkdir "${dir}" create it if it doesn't exist.
  • mv "${1}" "${dir}/${name}" move the dir to the new location.
  • export -f move export the function so it can be called in subshell

Find function

  • find /radacct look in /radacct dir
  • -type d -mindepth 2 -maxdepth 2 look for dirs in dirs.
  • -name '*detail*' which contain the word detail.
  • -exec bash -c 'move "$0"' {} \; and execute the move function, supplying the name of the dir as argument.

Note that I will add more details and test it later today.

To perform this weekly, use a job.

Upvotes: 2

Related Questions