How do I loop through a directory? I know there is for f in /var/files;do echo $f;done;
The problem with that is it will spit out all the files inside the directory all at once. I want to go one by one and be able to do something with the $f variable. I think the while loop would be best suited for that but I cannot figure out how to actually write the while loop.
Any help would be appreciated.
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).
Use the ls Command to List Directories in Bash. We use the ls command to list items in the current directory in Bash. However, we can use */ to print directories only since all directories finish in a / with the -d option to assure that only the directories' names are displayed rather than their contents.
To see a list of all subdirectories and files within your current working directory, use the command ls . In the example above, ls printed the contents of the home directory which contains the subdirectories called documents and downloads and the files called addresses.
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.
A simple loop should be working:
for file in /var/* do #whatever you need with "$file" done
See bash filename expansion
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