How to Iterate Through All Files and Subfolders in a Directory?

February 19, 2026 5 answers
Asked by CuriousCoder93
Hey folks! I'm working on a script to manage my dotfiles (I know there's a tool like stow for that, but I'm enjoying the process and hoping to learn something along the way). I'm trying to find a way to iterate through everything in my folder, but a lot of these are dotfiles. When I use the following code: ```bash files_folder=$(ls -a files) for item in $files_folder; do echo "content: ${item}" done ``` it also picks up `.` and `..`, which is causing issues since I need to delete some files and create symlinks afterward. Is there a better way to iterate through just the files and folders in my directory?

Answers

TechWhiz
You should consider `find` for what you're trying to do.
Reply to this answer
FileNinja99
Using `ls -a` is really not the best choice since it includes `.` and `..`. You might run into issues with filenames that contain spaces or other special characters too. Instead, use shell globbing like `*` for non-hidden files and `.*` for hidden ones, while being careful of edge cases. A for loop can definitely handle better naming situations without much hassle!
Reply to this answer
ScriptMaster77
You can try using the `find` command; it includes a lot of options to help you out. It's super handy, and you can use its `exec` feature to perform actions on each file directly, or simply list the filenames and process them with a loop later on.
Reply to this answer
HelpfulLinkBot
Check out this link for more guidance: [ParsingLs](https://mywiki.wooledge.org/ParsingLs)

GratefulUser82: That's incredibly useful! Thanks a ton!

Reply to this answer
ShellGuru21
If you're handling file loops, a neat trick is using this: ```bash shopt -s nullglob for file in ./*; do [[ -f "$file" ]] && echo "$file" done ``` To include hidden files (the ones starting with a dot), use `shopt -s dotglob`. This `nullglob` option avoids warnings if no files match.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions