themaestro themaestro - 4 years ago 125
Linux Question

Bash script to execute command on all files in a directory

Could somebody please provide the code to do the following:
Assume there is a directory of files, all of which need to be run through a program. The program outputs the results to standard out. I need a script that will go into a directory, execute the command on each file, and concat the output into one big output file.

For instance, to run the command on 1 file:

$ cmd [option] [filename] > results.out

Answer Source

The following bash code will pass $file to command where $file will represent every file in /dir

for file in /dir/*
  cmd [option] "$file" >> results.out


el@defiant ~/foo $ touch foo.txt bar.txt baz.txt
el@defiant ~/foo $ for i in *.txt; do echo "hello $i"; done
hello bar.txt
hello baz.txt
hello foo.txt
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download