Bash: for file in if exists?

So,

for f in *.c; do echo "That $f is the best C code I have ever seen"; done 

if there are no c files, gladly print

 That *.c is the best C code I have ever seen 

which is undesirable. Is there an elegant way to correct / express the fact that I want to completely skip the loop if there are no c files?

+4
source share
4 answers

Set the nullglob parameter. Then the extension will be empty if there is no match.

 shopt -s nullglob for f in *.c; do 

Please note that this is a bash-specific constructor, it will not work under normal sh .

+7
source
 n=`ls -1 *.c 2> /dev/null | wc -l` if [ $n != 0 ] then for f in *.c; do echo "That $f is the best C code I have ever seen"; done fi 
0
source

In Bash, shopt -s nullglob will call globes that don't match any files to return an empty extension, not an identifier.

For POSIX, something like

 case *.c in '*.c' ) echo no match ;; esac 

with an obvious pathological exception that you might need separately to check if there is one match file whose name is literally *.c .

0
source

Try:

 for f in `ls -1 *.c`; do echo That $f is the best C code I have ever seen done 
-2
source

All Articles