How can I play all MP3 files in a folder using a bash script?
Asked by
drizzling again
I'm learning bash and trying to enhance my project management script. One feature I want to add is a command that plays every MP3 file in a specific folder after I open my project in my IDE. I've written this loop:
```bash
for i in *.mp3; do
ffplay -nodisp -autoexit "/home/scottishcomedian/Music/bash_bullshit/$i"
done
```
When I execute it, I just get a blank console. What could I be doing wrong? Any advice would be appreciated!
Answers
You might also want to check if there are actually MP3 files in that folder. Adding some debug lines could help. Try doing this before your loop:
```bash
echo "Expecting files in: /home/scottishcomedian/Music/bash_bullshit"
ls /home/scottishcomedian/Music/bash_bullshit/*.mp3
```
This will let you see if the files are there before you try to play them!
Reply to this answer
You can also simplify things by not hardcoding the path inside the loop. Either use a parameter to pass the folder's location or switch to that directory first with `cd`:
```bash
(cd /home/scottishcomedian/Music/bash_bullshit && for i in *.mp3; do
ffplay -nodisp -autoexit "$i"
done)
```
This keeps your script clean and ensures it looks in the right place.
Reply to this answer
If you're still running into issues, consider redirecting stderr to check for errors from ffplay. You can do something like this:
```bash
touch error_log.txt
for i in /home/scottishcomedian/Music/bash_bullshit/*.mp3; do
ffplay -nodisp -autoexit "$i" 2>> error_log.txt
done
```
This way, if any errors occur, they'll be logged in the error_log.txt file for you to review later.
6th seed packet: I have no idea what stderr means, but I'll look it up! Thanks for the advice.
Reply to this answer
First, make sure youโre running the script in the right directory. If your working directory doesnโt contain MP3 files, your script wonโt find any. You can adjust your loop to specify the full path for the MP3s:
```bash
for i in /home/scottishcomedian/Music/bash_bullshit/*.mp3; do
ffplay -nodisp -autoexit "$i"
done
```
This way, it directly scans the target folder for MP3s.
aperture.priority.: Thanks! I think I was confused about the directory. I'll give that a try!
Reply to this answer
Try using the `find` command to avoid ambiguity with file matches. Run this snippet:
```bash
find /home/scottishcomedian/Music/bash_bullshit/ -type f -name '*.mp3'
```
This will give you a list of all the MP3 files which you can loop over directly from that output. Super handy!
Reply to this answer
Add your answer
Answers are reviewed before publication.
antique clock pendulum: Great tip! I'll make sure to check the contents before running the player.