Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute command for every file in the current dir

Tags:

How can i execute a certain command for every file/folder in the current folder?

I've started with this as a base script, but this seems that its only working when using temporary files, and i dont really like the ideea. Is there any other way?

FOLDER="."; DIRS=`ls -1 "$FOLDER">/tmp/DIRS`;  echo >"/tmp/DIRS1"; while read line ; do     SIZE=`du "$FOLDER$line"`;     echo $SIZE>>"/tmp/DIRS1"; done < "/tmp/DIRS"; 

For anyone interested, i wanted to make a list of folders, sorted by their size. Here is the final result

FOLDER="$1"; for f in $FOLDER/*; do    du -sb "$f"; done | sort -n | sed "s#^[0-9]*##" | sed "s#^[^\./]*##" | xargs -L 1 du -sh | sed "s|$FOLDER||"; 

which leads to du -sb $FOLDER/* | sort -n | sed "s#^[0-9]*##" | sed "s#^[^\./]*##" | xargs -L 1 du -sh | sed "s|$FOLDER||";

like image 759
Quamis Avatar asked Nov 10 '10 09:11

Quamis


People also ask

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

All of them are simple one-liner shell scripts that displays the given string(s) using "echo" command in the standard output. Again, I make the second script executable and run it and so on. Well, there is a better way to do this. We can run all scripts in a directory or path using "run-parts" command.

Which command is used to list all the files in your current directory in Linux?

The ls command is used to list files. "ls" on its own lists all files in the current directory except for hidden files.


2 Answers

Perhaps xargs, which reinvokes the command specified after it for each additional line of parameters received on stdin...

ls -1 $FOLDER | xargs du 

But, in this case, why not...

du * 

...? Or...

for X in *; do     du $X done 

(Personally, I use zsh, where you can modify the glob pattern to only find say regular files, or only directories, only symlinks etc - I'm pretty sure there's something similar in bash - can dig for details if you need that).

Am I missing part of your requirement?

like image 77
Tony Delroy Avatar answered Oct 13 '22 02:10

Tony Delroy


The find command will let you execute a command for each item it finds, too. Without further arguments it will find all files and folders in the current directory, like this:

$ find -exec du -h {} \; 

The {} part is the "variable" where the match is placed, here as the argument to du. \; ends the command.

like image 22
Daniel Schneller Avatar answered Oct 13 '22 02:10

Daniel Schneller