Shopt command search issue

102 Views Asked by At

I have a current script to get all .jpg and .jpeg files in a folder, my bash script is as follows

shopt -s nullglob
CURRENT_IMAGE_FILES=($DIR/*.jpg $DIR/*.jpeg)
echo ${#CURRENT_IMAGE_FILES[@]}
shopt -u extglob

The results being output are as follows (1.jpg , 3.jpg , 5.jpg , 2.jpeg ,4.jpeg). Being that the serach follows all .jpg first then the rest of the .jpeg being found.

The issue with this code is that it get's all jpg files first then gets all jpeg files. I however want to get all jpg and jpeg files in increment as follows (1.jpg, 2.jpeg, 3.jpg, 4.jpeg, 5.jpg)

1

There are 1 best solutions below

2
On

Once extglob is set, it's as simple as

shopt -s nullglob extglob
CURRENT_IMAGE_FILES=("$DIR"/*.@(jpg|jpeg))

Since a single pattern will match all the target files, they will be sorted together, as opposed to sorting the files that match just *.jpg, then sorting the files that match *.jpeg. Of course, sorting will only work if the file names are in the right format. 10.jpg would still come before 1.jpg, but there isn't much you can do about that using only globs.