1834944 Members
1988 Online
110071 Solutions
New Discussion

Disable error messge

 
O'lnes
Regular Advisor

Disable error messge

When use 'ls' to list a not available file (eg. `ls testfile` ) , then it would pop up error message `testfile not found ' , how can i disable such error message (except output the error to null value ( 2 > /dev/null ) ? Thanks.
Andy
5 REPLIES 5
James R. Ferguson
Acclaimed Contributor

Re: Disable error messge

Hi:

You already have the answer. Redirect stderr to /dev/null. You can still interrogate the return value from 'ls' to determine whether there were any errors or if all file(s) were listed. For instance:

# ls -l /tmp/myfile /tmp/yourfile 2>/dev/null
# echo $?

...would return the listing for if it were present, but would suppress the message "/tmp/yourfile not found" if was not present. The return value from 'ls' would be non-zero to denote the an exception condition, however.

Regards!

...JRF...
O'lnes
Regular Advisor

Re: Disable error messge

Is there other methods or command can also disable the messaage? Thanks.
Andy
James R. Ferguson
Acclaimed Contributor

Re: Disable error messge

Hi:

No. The segregation of normal output (stdout) and error messages into 'stdout' and 'stderr', respectively, is expected for well-written utilities (and scripts). It allows just what you have seen.

Regards!

...JRF...
Brian M Rawlings
Honored Contributor

Re: Disable error messge

One other way occurs to me, however. You could create an alias that you would use instead of 'ls', which would run either the redirect to /dev/null sequence outlined by JRF, or possibly something else like

ls $1 2>&1 | grep -v " not "

(presuming that unix file names will not have spaces)

I'm not in a position to try this approach just now, but it should work with some tweaking as needed.

I also wouldn't recommend making an alias named ls, since, as JRF points out, an error upon failure is normal behavior for ls (and most commands, other than those that intentionally fail silently). The results might not be predictable or useful if other scripts were to run with ls behaving as you want it to. Just make yourself a different command that acts like you want it to, via the alias facility.

Hope this helps. Regards, --bmr
We must indeed all hang together, or, most assuredly, we shall all hang separately. (Benjamin Franklin)
O'lnes
Regular Advisor

Re: Disable error messge

thx all.
Andy