Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I’m looking for a method to scan a directory (not recursive) and tar it using the original folder name, and then delete the folder (so I will have only the folder compressed) Anyone has the command for that?

share|improve this question
What if the directory contains sub-directories? – enzotib Sep 22 '11 at 9:03
Could you rephrase your question? It's not clear whether you want to tar a directory and then remove it, or tar subdirectories and then remove those subdirectories. In the latter case, what about files in the directories? – Lekensteyn Sep 22 '11 at 9:36
up vote 3 down vote accepted

I can suggest the following one-liner (supposing the current directory is the parent of the directories to backup):

for f in */; do tar -czf "${f%/}.tar.gz" "$f"; rm -rf "$f"; done

To change each folder name to lowercase, and substitute spaces with underscore:

for f in */; do f="${f// /_}"; f="${f,,}"; tar -czf "${f%/}.tar.gz" "$f" && rm -rf "$f"; done_
share|improve this answer
find combined with the -maxdepth 1 option also takes hidden directories; shopt -s dotglob will do that too for this for – Lekensteyn Sep 22 '11 at 9:37
thanks! was helpful, is there a way to convert the names to "safe name" (i.e My Folder = my_folder) delete the spaces and make lowercase each tar? – Amir Ashkenazi Sep 23 '11 at 9:37
I edited my answer for this your new request. By the way, you should remove this answer (that is not really an answer) and post it as a comment to my answer. – enzotib Sep 23 '11 at 9:46

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.