Ubuntu – Running a Bash while loop over all similar files


I would like to write a while loop in Bash that runs over all instances of files that are of the form of


for example, 1.tst, 2.tst, … 50.tst.

I do not want it to run over the file tst.tst.

How would I go about writing this? I assume I will need a boolean phrase and [0-9]* somewhere in there, but I am not entirely sure on the syntax.

Best Answer

If you only need to exclude alphabetic names like your example tst.tst you could use a simple shell glob

for f in [0-9]*.tst; do echo "$f"; done

With bash extended globs (which should be enabled by default in Ubuntu)


$ ls *.tst
1.tst  2.tst  3.tst  4.tst  50.tst  5.tst  bar.tst  foo.tst

then +([0-9]) means one or more decimal digits:

for f in +([0-9]).tst; do echo "$f"; done

You can check whether extended globbing is enabled using shopt extglob and set it if necessary using shopt -s extglob (and unset using set -u extglob).

Related Question