Bash scripting and using TAR to archive folders, how to grab the 5 most recent folders in a folder?

StackOverflow https://stackoverflow.com/questions/21631838

  •  08-10-2022
  •  | 
  •  

Question

I have a script that archives a bunch of directories using tar, below is the snippet..

run_tar()
{
  clear
  echo "***"
  echo "This can take up to an hour, please wait..."
  echo "***"
  tar -X $BASE/synclive_exclude.list -cf - /usr2/docs /usr2/devel_backup /usr2/devel_config /usr2/devel_logs /usr2/devel_reports /usr2/devel_snapshots /usr2/doc-files | gzip > $DUMP_DIR/stage/usr2.tar.gz &
  wait
}

The problem I am running into is.. for one specific directory above.. /usr2/devel_snapshots the directory is large and consists of daily backups..

The folders within this folder are..

drwxrwxrwx    3 root     system         8192 Feb 01 11:15 201402011115
drwxrwxrwx    3 root     system         8192 Feb 02 11:15 201402021115
drwxrwxrwx    3 root     system         8192 Feb 03 11:15 201402031115
drwxrwxrwx    3 root     system         8192 Feb 04 11:15 201402041115
drwxrwxrwx    3 root     system         8192 Feb 05 11:15 201402051115
drwxrwxrwx    3 root     system         8192 Feb 06 11:15 201402061115

Is it possible to only grab the most recent 5 folders from /usr2/devel_snapshots in my tar command instead of the whole folder?

How would I go about making that work?

The OS is AIX 7.1 64bit

Thank you.

Was it helpful?

Solution

You can try with something like:

find /usr2/devel_snapshots \
    -type d \
    -maxdepth 1 \
    -mindepth 1 |
        sort -r |
        head -5 | 
        xargs tar -X $BASE/synclive_exclude.list -cf - \
            /usr2/docs /usr2/devel_backup /usr2/devel_config \
            /usr2/devel_logs /usr2/devel_reports /usr2/doc-files | 
                gzip > $DUMP_DIR/stage/usr2.tar.gz &

ls, sort and head will get the latest 5 directories and with xargs you can give the results as parameter to the tar command

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top