I have a directory with the following files:
- file1.jpg
- file2.jpg
- file3.jpg
- file1.png
- file2.png
- file3.png
I have a bash function named filelist
and it looks like this:
filelist() { if [ "$1" ] then shopt -s nullglob for filelist in *."$@" ; do echo "$filelist" >> created-file-list.txt; done echo "file created listing: " $@; else filelist=`find . -type f -name "*.*" -exec basename \{} \;` echo "$filelist" >> created-file-list.txt echo "file created listing: All Files"; fi }
Goal: Be able to type as many arguments as I want for example filelist jpg png
and create a file with a list of files of only the extensions I used as arguments. So if I type filelist jpg
it would only show a list of files that have .jpg.
Currently: My code works great with one argument thanks to $@
, but when I use both jpg and png it creates the following list
- file1.jpg
- file2.jpg
- file3.jpg
- png
It looks like my for loop is only running once and only using the first argument. My suspicion is I need to count how many arguments and run the loop on each one.
An obvious fix for this is to create a long regex check like (jpg|png|jpeg|html|css)
and all of the different extensions one could ever think to type. This is not ideal because I want other people to be free to type their file extensions without breaking it if they type one that I don't have identified in my regex. Dynamic is key.