Bash For Loop to List MP3 Files
A simple for loop in bash to print all .mp3 file names to a text file is:
for file in *.mp3; do
echo "$file" >> music_list.txt
done
Here’s a breakdown of what each part does:
-
for file in *.mp3; do: This starts the loop.for file: This creates a variable namedfilethat will hold the name of each file one by one.in *.mp3: This tells the loop to look for all files ending with.mp3in the current directory.do: This marks the beginning of the commands to be executed for each file.
-
echo "$file" >> music_list.txt: This is the command that gets run for each file.echo "$file": Theechocommand prints the value of thefilevariable, which is the current mp3’s name. The quotes around$fileare important because they prevent issues with file names that have spaces.>> music_list.txt: This part is called “redirection.” The>>operator appends the output of theechocommand to a file namedmusic_list.txt. If the file doesn’t exist, it will be created. If you use a single>instead, it will overwrite the file each time.
-
done: This marks the end of the loop.
This script will go through every .mp3 file in your directory, print its name, and add it as a new line to the music_list.txt file.