Search code examples
linuxbashzip7zip

Bash script to automatically zip different subfolders and store the zipped files into a special folder with dated names


My directory structure is thus:

\myproject\
     src\
     include\
     zipdir\
     .vscode\
     auto7zip.bat
     

There are specific files from within .vscode\ subfolder that I would like to archive, and not the entire folder.

On windows, the auto7zip.bat file has the following content:

@ECHO OFF
SETLOCAL EnableExtensions EnableDelayedExpansion

Set TODAY=%date%
ECHO %TODAY%
    
set path="c:\Program Files\7-Zip";%path%
set projectdir=%CD%
set "zipdirsrc=%projectdir%\src"
set "zipdirinc=%projectdir%\include"
set "zipdirothers=%projectdir%\.vscode"
set "movedir=%projectdir%\zipdir"

pushd %zipdirsrc%
ECHO Zipping all contents of %zipdirsrc% and moving archive src to %movedir%
7z a -tzip "%movedir%\src_%TODAY%.zip" -r "%zipdirsrc%\*.*" -mx5
ECHO SRC Task Complete ...

pushd %zipdirinc%
ECHO Zipping all contents of %zipdirinc% and moving archive include to %movedir%
7z a -tzip "%movedir%\include_%TODAY%.zip" -r "%zipdirinc%\*.*" -mx5
ECHO INCLUDE Task Complete ...

pushd %zipdirothers%
ECHO Zipping all other contents of %zipdirothers% and moving archive others to %movedir%
7z a -tzip "%movedir%\others_%TODAY%.zip" -r "%zipdirothers%\*.json" "%zipdirothers%\Makefile" "%zipdirothers%\Makefile*.mk" "%zipdirothers%\windows.vcxproj" "%zipdirothers%\nbproject\" -mx5
ECHO OTHERS Task Complete ...

EXIT /B 0

This batch file, if run today (July 2nd, 2021) on windows with 7zip installed creates include_02-07-2021.zip which is the zipped version of include\, src_02-07-2021.zip which is the zipped version of src\ and others_02-07-2021.zip which is the zipped version of the specific files from the .vscode\ directory. These zipped files are created automatically inside the zipdir\ directory.

Is there an equivalent bash script that when run from within \myproject\ accomplishes the same thing on linux distributions, in particular, ubuntu?


Solution

  • This should do what you need.

    #!/bin/bash
    
    today=$(date +'%d-%m-%Y')
    echo $today
    
    movedir=../zipdir
    
    function backup() {
        if [[ -n $2 ]]; then
            newname="$2"
        else
            newname="$1"
        fi
        cd "$1"
        [[ -z $custom ]] && custom="./*"
        echo "Zipping all contents of ./$1 and moving archive $newname to $movedir"
        zip "$movedir/${newname}_$today.zip" -r $custom  -9
        unset custom
        cd ..
    }
    
    unset custom
    
    backup src
    backup include
    custom='./*.json ./Makefile ./Makefile*.mk ./windows.vcxproj ./nbproject/'
    backup .vscode others
    
    

    Update 1:

    • Removed irrelevant part of answer
    • Updated script to exclude root directory from archive by changing into relevant directory (since request was clarified by OP).