Sign up ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have the following commands that I would like to run inside each subdirectory of the current working directory. Here are the commands:

OUTPUTFN=`basename $PWD`
cat *.xml > $OUTPUTFN.txt
mv $OUTPUTFN.xml ..

There are over 700 folders in this directory, I want it to go into each, execute those four commands, and then go to the next, execute the commands, and repeat. I've tried combining several samples from this site with my commands but can't get it to work.

share|improve this question
All directories are listed inside the same directory. There is a maximum of one level. –  jlacroix82 Jun 28 '12 at 16:23

1 Answer 1


for DIR in *; do
    [ -d "$DIR" ] && cat "$DIR"/*.xml > "$DIR.xml"


for DIR in *; do [ -d "$DIR" ] && cat "$DIR"/*.xml > "$DIR.xml"; done

How it works

  • Bash expands * to all files and directories in the current directory.

  • for DIR in *; do ... done goes through these and executes ... for each one.

    In each case, $DIR holds the name of the current entry.

  • [ -d "$DIR" ] && ... checks if $DIR is indeed a directory (and not a file).

    If it is, ... gets executed.

  • cat "$DIR"/*.xml > "$DIR.xml" does precisely what your four lines of code do.

share|improve this answer
I'm testing it now. One question about this line: cat "$DIR"/*.xml > "$DIR.xml" Since $DIR.xml" is itself an XML file, would it cat itself back into $DIR.xml again since the output file qualifies as the very thing it's merging? –  jlacroix82 Jun 28 '12 at 16:50
This isn't an issue since cat operates on all .xml files in $DIR, while $DIR.xml is located in the parted folder. –  Dennis Jun 28 '12 at 16:56
Thank you, it works! –  jlacroix82 Jun 28 '12 at 18:58

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.