Antonio Ocampo
Antonio Ocampo

Reputation: 61

TXT File verification on shell script

I'm working on a shell script that does certain process on txt files only if it does exist, however this test loop doesn't work, I wonder why? Thank you!

while [ -e '*.txt' ] do $process done

Upvotes: 0

Views: 307

Answers (2)

thb
thb

Reputation: 14464

If all on one line, your commands need semicolons as follows:

while [ -e '*.txt' ] ; do $process ; done

However, I don't think that [ -e '*.txt' ] does what you want. It looks for a file literally named '*.txt'.

It is not a neat solution, but this seems to work:

while stat --format='' *.txt >/dev/null 2>/dev/null  ; do $process ; done

One could probably use find or some other command instead of stat, but the idea is to pick a command that returns true if and only if at least one argument is supplied. Best would be to write your own command that returned 0 or 1 depending on argc.

However, also see @Thomas' reply. One suspects that his guess may be right.

Update: Here is a better answer:

at_least_one() { (($# > 0)) ; }
while at_least_one *.txt ; do $process ; done

Upvotes: 0

Thomas
Thomas

Reputation: 182073

Your while loop (once fixed) will run $process continuously, until all files named *.txt have been deleted. I don't see how that would be useful.

I'm guessing -- guessing, mind you -- that you intended to do something like this instead:

for f in *.txt; do $process; done

This will invoke $process once for each .txt file, setting $f to the name of the file. For instance,

for f in *.txt; do cat $f; done

will output the contents of each .txt file in the current directory.

Upvotes: 3

Related Questions