001-bash-loop
You can use a for loop with ls in Bash to iterate over files or directories listed by the ls command. Here's how you can do it:
Example 1: Loop through files in the current directory¶
for file in $(ls)
do
echo "File: $file"
done
This loop uses ls to get the list of files in the current directory and iterates over each file, printing its name.
Example 2: Loop through files with a specific extension¶
If you want to loop through only files with a specific extension, you can modify the ls command like this:
for file in $(ls *.txt)
do
echo "Text File: $file"
done
This will only loop through .txt files in the current directory.
Example 3: Using for with ls and find for nested directories¶
If you need to loop through files in subdirectories, you can use find in combination with a for loop:
for file in $(find . -type f)
do
echo "File: $file"
done
This will recursively find all files starting from the current directory (.) and print each file name.
Example 4: Loop through files in a directory and handle spaces in filenames¶
Using $(ls) can cause issues if filenames contain spaces or special characters. A safer way is to use a for loop with find or glob pattern matching directly:
for file in * # Match all files in the current directory
do
echo "File: $file"
done
This will handle filenames with spaces correctly.
Example 5: Using ls with -1 option for a line-by-line output¶
Using ls -1 (note the -1 flag) lists files one per line, and you can loop through them like this:
for file in $(ls -1)
do
echo "File: $file"
done
Let me know if you'd like more examples or explanations!