Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how many arguments 1

Status
Not open for further replies.

ogniemi

Technical User
Nov 7, 2003
1,041
PL

simple loop:


for i in file*;do if if_no_file*;then echo "there are no files begin with file";else process file(*);done

how to check after "do" that $i is empty and then print echo "there are no files begin with file"?

[ $number_of_arguments_i -eq 0 ] && echo "there are no files begin with file" || process $i








 
how about:

numfiles=0
for i in $(ls file* 2>/dev/null)
do
(( numfiles=numfiles+1 ))
process $i
done
if (( numfiles==0 ))
then
echo no files to process
fi


HTH,

p5wizard
 
for i in file*; do
[ "$i" = 'file*' ] && echo "there are no files begin with file" || process $i
done


Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
Just for completeness, to avoid the extra variable, and the test on every loop you could
Code:
for i in $(ls file* 2>/dev/null || echo no files beginning with file\*)
do
  process $i
done

Ceci n'est pas une signature
Columb Healy
 
Oops - trying to be too clever! :~/ My code snippet would only work if the 'echo no files...' were output to stderr, otherwise they get caught up in the for loop. MkII version
Code:
for i in $(ls file* 2>/dev/null || { exec >&2; echo no file\* files found; } )
do
  echo $i
done

Ceci n'est pas une signature
Columb Healy
 
exec construction is not necessary I believe:

Code:
for i in $(ls file* 2>/dev/null || echo no file\* files found; >&2 )
do
  echo $i
done

as for the extra variable - ok but... you get a free count of processed files:

Code:
numfiles=0
for i in $(ls file* 2>/dev/null)
do
 (( numfiles=numfiles+1 ))
 process $i
done
if (( numfiles==0 ))
then
 echo "no files to process"
else
 echo "${numfiles} file(s) processed"
fi

OK it wasn't asked, but I threw that one in for free ;-)

And as always, PHV's code is compact and neat.


HTH,

p5wizard
 
p5wizard
I wasn't saying my version was best. It's a slow day and I got intreagued as to whether I could do it without the extra variable or the repetititve testing. Having done so, or rather having thought I'd done so, I couldn't resist boasting and pride came before a fall. In a real life script I would probably go for one of the simpler versions for maintainability.

Ceci n'est pas une signature
Columb Healy
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top