Tar and GZIP Folder Contents

« Back To Archive

2

Problem Statement:

A bash routine to create a GZIP tarball of a folder's contents with a single command. The tarball name is created using the folder name and the current time stamp. Just add this function to your bashrc file (usually in /etc/bashrc).

Dependencies:

linux, unix, bsd, macos x, bash

Example Usage:

technify$ cd /path/to/some/folder
technify$ tarball
function tarball() {
    pwd > /tmp/x
    awk -F/ '{print $NF}' /tmp/x > /tmp/y
    mydir=`cat /tmp/y`
    date >/tmp/x
    sed 's/  / /g' /tmp/x>/tmp/y
    sed 's/:/./g' /tmp/y>/tmp/x
    sed 's/ /./g' /tmp/x>/tmp/y
    awk -F. '{print $8 "." $2 "." $3 "." $4 $5}' /tmp/y>/tmp/x
    mydate=`cat /tmp/x`
    TARBALL=$mydir.$mydate
    date > /tmp/version.txt
    sudo cp /tmp/version.txt .
    echo "  Beginning the tar..."
    sudo tar -cf $TARBALL.tar *
    echo "  Gzipping the tarball..."
    sudo gzip $TARBALL.tar
    echo "  Successfully created $TARBALL.tar.gz"
}
  • George Flanagin

    Or you could do this:

    tar -zcf ~/`basename `pwd“.`date +%F`.tar.gz ./*

    Those are backquotes, which are bash’s way of giving you the result of some other shell command. It works like this:

    `pwd` => the present working directory.
    `basename …. ` => strips off the leading dirs, leaving you with only the final part of the dir name.
    `date +%F` => prints the date with dashes, as yyyy-mm-dd
    -zcf => creates the file as a prezipped tarball
    ./* => everything in this directory.

    • http://iconify.it Scott Lewis

      Nice. That’s a much more efficient approach.