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.

# 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
# $

# output directory
# - the same directory if empty
# - remember to use trailing slash, for example "/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"


Sample directories and files inside milosz home directory..

~milosz$ ls -1F

Execute the shell script.


List archives created inside /tmp directory.

~milosz$ ls -1 /tmp

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

~milosz$ tar tf /tmp/milosz_files.tgz

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 Linux Foundation Certified Engineer working for a successful Polish company as a system administrator and a long time supporter of Free Software Foundation and Debian operating system.

Gdansk, Poland