Traversing files in a given directory using a bash script
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
Traversing files in a given directory using a bash script
This seems like a question I should have no problem with, but I am. I'm trying to write a bash script that takes in one directory as an argument, traverses the files in the directory, and prints each file name that has a size of 0. However, I can't seem to get it to work properly. Here's what I've got so far:
Code:
#!/bin/bash
if [ -d "$1" ]; then
for file in "$1"; do
echo HELLO
done
fi
Of course, that's not doing what I want it to do right now, but I'm just trying to get it to say HELLO three times (there are three files in my target directory). At the moment, it only echoes HELLO once.
The "for file in" will be repeated for every element in the "$1" argument. There is only one, the directory you inputed.
Code:
for file in "$1"/*; do
A better way of doing it would be to use the find command.
Code:
if [ -d "$1 ]; then
find "$1" -type f -empty
If you don't want to recurse subdirectories, add the option "-maxdepth 1". Using: for file in "$1"/*; do will return all filenames, so you would still need to test that it is a regular file and that it is a zero length file.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.