Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run shell script for every file in directory

I have a bunch of files in a directory all named YYYY_MM_DD

-rw-r--r-- 1 root root 480K Apr 21 13:17 2012_04_05
-rw-r--r-- 1 root root 483K Apr 21 13:17 2012_04_06
-rw-r--r-- 1 root root 484K Apr 21 13:17 2012_04_07
-rw-r--r-- 1 root root 480K Apr 21 13:17 2012_04_08
-rw-r--r-- 1 root root 344K Apr 21 13:17 2012_04_09
-rw-r--r-- 1 root root  66K Apr 21 13:17 2012_04_10
-rw-r--r-- 1 root root 461K Apr 21 13:17 2012_04_11
-rw-r--r-- 1 root root 475K Apr 21 15:09 2012_04_17
-rw-r--r-- 1 root root 480K Apr 21 15:10 2012_04_18
-rw-r--r-- 1 root root 474K Apr 21 15:10 2012_04_19
-rw-r--r-- 1 root root 474K Apr 21 15:10 2012_04_20

I have a shell script that accepts a file as a paramater and calculates figures based on the data in the file, i call the script like this

sh Calculate.sh MyFile

I want to run this shell script for every file in this directory.

How would i go about doing this, xargs ??

like image 955
general exception Avatar asked Apr 21 '12 14:04

general exception


People also ask

How do you loop through every file in a directory?

To loop through a directory, and then print the name of the file, execute the following command: for FILE in *; do echo $FILE; done.

How do I loop all files in a directory in bash?

The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).

How do I run all files in a directory in Linux?

We can run all scripts in a directory or path using "run-parts" command. The run-parts command is used to run scripts or programs in a directory or path. One disadvantage with run-parts command is it won't execute all scripts. It will work only if your scripts have the correct names.


2 Answers

Have you tried the find command with execution ?

My sample will echo the files, but you can call a shell script with the filename as a parameter

find . -maxdepth 1 -type f -exec echo {} \;
like image 94
MrJames Avatar answered Sep 20 '22 18:09

MrJames


A simple for loop in the shell:

for file in *; do sh Calculate.sh "$file"; done
like image 39
glenn jackman Avatar answered Sep 23 '22 18:09

glenn jackman