How to archive every directory in current location

Today I needed to archive every non-hidden directory in several different locations. I do not like to repeat myself so after a while I quickly created shell script to accomplish this task.

Shell script

Simple shell script which you can find below this paragraph will create single archive containing every file found inside current location and then perform archive operation on every directory.

#!/bin/bash
# Archive every non-hidden directory in current location
# Optionally it will also archive every file inside current location (it ignore dot files)
#
# $ cd /x/y/z
# $ archive.sh

# output directory
# - the same directory if empty
# - remember to use trailing slash, for example "/tmp/"
output_path="/tmp/"

# ****** optional
# first step - take care of files in current directory
archive_file="${output_path}$(pwd | awk -F/ '{print $NF}')_files.tgz"
find . -maxdepth 1 -type f -not -name ".*"  -exec tar czf "${archive_file}" {} +

# ****** main
# second step - take care of directories
for dir in */; do
  # remove trailing slash
  dir=`echo $dir | tr -d '/'`
  tar czf "${output_path}${dir}.tgz" "$dir"
done

Example

Sample directories and files inside milosz home directory..

~milosz$ ls -1F
Documents/
Downloads/
ideas.org
passwords.kdb

Execute the archive.sh shell script.

~milosz$ archive.sh

List archives created inside /tmp directory.

~milosz$ ls -1 /tmp
Documents.tgz
Downloads.tgz
milosz_files.tgz

List contents of the archive containing files found inside milosz home directory.

~milosz$ tar tf /tmp/milosz_files.tgz
./ideas.org
./passwords.kdb

Ending note about the find command

Although it is not POSIX compliant, please notice that you can use -not option to exclude dot files as it is much more readable then using escaped parentheses to negate expression.

Milosz Galazka's Picture

About Milosz Galazka

Milosz is a system administrator working for a successful Polish company and a long time supporter of Free Software Foundation and Debian operating system.

Gdansk, Poland https://sleeplessbeastie.eu