That's not an array at all. x
is a simple string variable, and looping over it without quoting it will split it on whitespace.
That's problematic if you have file names with spaces or other shell metacharacters in them, but undramatic if your simple file names are representative. In that case, just ... sort
.
x=$(find . -name "*.mp4" -printf "%f\n" | sort)
printf "File -> %s\n" $x
Not quoting your string variables comes with a ton of warnings, though. Probably actually do use an array.
readarray -d '' x < <(find . -name "*.mp4" -print0 | sort -z)
printf "File -> %s\n" "${x[@]}"
(readarray
requires Bash 4+ so will not work out of the box on MacOS. find -print0
and its companion sort -z
is a GNU extension which is not portable to POSIX / non-GNU systems.)
If all the files are in the current directory, find
is completely overkill; just use the shell's built-in wildcard expansion, which sorts by default.
printf "File -> %s\n" *.mp4
If you need to loop over the files and do something more useful than just print each, you don't need a variable. Just loop directly over the wildcard expansion.
for file in *.mp4; do
# This is where we do something more useful than ...
printf "File -> %s\n" "$file"
done
Notice how you need to quote "$file"
inside the loop, too. It will look like it works without quoting when you test it with trivial file names, but break in spectacular and hard-to-debug ways when you run it on real files.