Server Fault is a question and answer site for system and network administrators. 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 trying to build a bash one-liner to loop over the directories within the current directory and tar the content into unique tars, using the directory name as the tar file name. I've got the basics working (finding the directory names, and tarring them up with those names) but my loop tosses some error messages and I can't understand where it's getting the commands its trying to run.

Here's the mostly-working one-liner:

for f in `ls -d */`; do `tar -czvvf ${f%/}.tar.gz $f`;done

The "strange" output is:

-bash: drwxrwxr-x: command not found
-bash: drwxr-xr-x: command not found
-bash: drwxr-xr-x: command not found
-bash: drwxrwxr-x: command not found

What portion of the command that I'm running do I not understand and that's generating that output?

share|improve this question
up vote 2 down vote accepted

You need to remove the backtics around your tar command. You also might want to pipe the ls through xargs to make sure bash picks up all the directories correctly:

for f in `ls -d */ | xargs`; do tar -cvzf ${f%/}.tar.gz $f; done

The backticks are capturing the ouput of tar and attempting to execute that as a command in each iteration of the loop. The first thing tar prints when you use a -v option is the permissions on each file (e.g. the drwxrwxr-x). In this case, you want bash to execute the tar command, not capture the output.

share|improve this answer
Most excellent - thanks for both the resolution, and more importantly for explaining the what and why. Highly appreciated! – cori Jan 28 '10 at 5:45

bjlaub is correct regarding the backticks around tar, however you don't need to use ls:

for file in */

will do the trick and will properly handle directory names with spaces.

share|improve this answer
Indeed you're correct. Good to know :) – bjlaub Jan 28 '10 at 5:30
super, thanks for the tip! – cori Jan 28 '10 at 5:45

The other answers here are good, but I wanted to add another option in case you need to get just directories and not symbolic links, etc:

for f in `find -maxdepth 1 -type d` | do -cvzf ${f%/}.tar.gz $f; done 

Hope this helps!

share|improve this answer

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.