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||";
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.
The ls command is used to list files. "ls" on its own lists all files in the current directory except for hidden files.
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With