Re: ls: avoiding error msg on non-existant file

[email protected] (Bob Proulx)
Newsgroups gmane.comp.gnu.fileutils.bugs
Message-ID <[email protected]>
Karl O. Pinc <[email protected]> [2002-11-28 22:41:18 -0600]:
> Well, there is a solution, but I don't like it much.

Hmm...  How about this suggestion below?

> Here's the task at hand.  My pwd contains
> files named 'uN' where 'N' is an integral version number.  I want
> the last version number, if there is one.  Here's my code:
> 
> last=$(for f in u* ; do
>          [ -e "$f" ] && echo "$f" ;
>        done | cut -c 2- | sort -n | tail -n 1 )

Functional.  But I see what you mean about it.

> (Except This is a translation into pure shell.
> I'm writing in php and using php's exec() (which is really system(3))
> instead of $() to produce the vaue for $last.  And the real
> code abstracts out the magic numbers like the 'u' and the number 2.
> FWIW, php's exec() has an implicit 'tail -n 1' built in.)

Ew.  I am well versed with perl but not php.  I hear they are deeply
related.  So for now I will stick with shell for the examples.

> Really, I'm in search of an idiom to take the result of shell's pattern
> expansion and pipe it somewhere, except the shell returns the pattern
> itself when there's nothing in the fs which matches and I want nothing
> at all in that case.

How about this as a possibility?  Still using 'ls'.  (I guess I could
have used 'echo * | tr " " "\012"' but I think this is more clear.)

It uses grep to extract only matching patterns, adjust to fit your
need.  I don't think any errors would normally occur and so none need
to be ignored.

  last=$(ls | grep -E '^u[0-9]+' | cut -c 2- | sort -n | tail -n 1)

> Oh well.  It's shell.  How elegent can it be made anyhow?

I actually like the shell quite a bit for many tasks.  The shell is
both powerful and weak at the same time.  The art is to play to the
strengths.

Bob
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.