If the files names are simple (no spaces, no newlines, no characters that ls needs to encode with a ?
) then, maybe !! , you can get away with:
IFS=$' \t\n'; for s in $(ls -v folder/*.script.sh); do printf '%s\n' "$s"; done
In this case, ls
will sort by version number -v
(quite similar to numeric value).
But in general, it is a bad idea to parse (process) the output of ls
.
This is better:
shopt -s nullglob
for s in folder/?{,?{,?{,?}}}.script.sh
do printf '%s\n' "$s"
done
Which will list (in alphabetical order, which is equivalent to numerical order if the characters before .script.sh
are only numbers) by each character up to four characters (numbers).
The idea is that brace expansions happen before pathname expansion. The brace expansion will convert and expand the ?{,?{,?{,?}}}.script.sh
to
?.script.sh ??.script.sh ???.script.sh ????.script.sh
And then, the pathname expansion will find all file that match each pattern sorting each pattern in turn.
If none of the options above are a solution, you will need to use sort
:
printf '%s\n' *.script.sh | sort -n | xargs echo
Which becomes even more complex if there is a folder
prefix:
printf '%s\n' folder/*.script.sh | sort -n -k 1.8 | xargs echo
Where the 8 is the number of characters (bytes) in the word folder
and the following /
plus one (1).
You will need to replace the echo
with sh
to execute each script.
This will work correctly if no file name contains newlines.
If it is possible that filenames may contain newlines, use this:
printf '%s\0' folder/*.script.sh | sort -zn -k 1.8 | xargs -0 -I{} echo '{}'
Again, replace the echo
with a sh
(or bash
) to execute the scripts.
for s in *.script.sh; do printf '%s\n' "$s"; done
should list the scripts in lexicographical order. Is that the order you need? If that is not what you need, the questions multiply: Are the numbers N only one digit? Do the numbers have leading zero(s)? etc … etc … – Nov 16 '18 at 18:52man run-,parts
. – waltinator Nov 16 '18 at 19:44linux
&bash
regardless of the content and there's nothingbash
-specific here (and it's already taggedshell
). You can always add it back if you think this is abash
question. – don_crissti Nov 16 '18 at 20:40folder
or that the solution has to be bash-specific) – don_crissti Nov 16 '18 at 20:52