How can I suppress error messages of a command?

LinuxBash

Linux Problem Overview


How can I suppress error messages for a shell command?

For example, if there are only jpg files in a directory, running ls *.zip gives an error message:

   $ ls *.zip
   ls: cannot access '*.zip': No such file or directory

Is there an option to suppress such error messages? I want to use this command in a Bash script, but I want to hide all errors.

Linux Solutions


Solution 1 - Linux

Most Unix commands, including ls, will write regular output to standard output and error messages to standard error, so you can use Bash redirection to throw away the error messages while leaving the regular output in place:

ls *.zip 2> /dev/null

Solution 2 - Linux

$ ls *.zip 2>/dev/null

will redirect any error messages on stderr to /dev/null (i.e. you won't see them)

Note the return value (given by $?) will still reflect that an error occurred.

Solution 3 - Linux

To suppress error messages and also return the exit status zero, append || true. For example:

$ ls *.zip && echo hello
ls: cannot access *.zip: No such file or directory
$ ls *.zip 2>/dev/null && echo hello
$ ls *.zip 2>/dev/null || true && echo hello
hello

$ touch x.zip
$ ls *.zip 2>/dev/null || true && echo hello
x.zip
hello

Solution 4 - Linux

I attempted ls -R [existing file] and got an immediate error. ls: cannot access 'existing file': No such file or directory

So, I used the following:

ls -R 2>dev/null | grep -i [existing file]*

ls -R 2>dev/null | grep -i text*

Or, in your case:

ls -R 2>dev/null | grep -i *.zip

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPeterView Question on Stackoverflow
Solution 1 - LinuxAJefferissView Answer on Stackoverflow
Solution 2 - LinuxBrian AgnewView Answer on Stackoverflow
Solution 3 - LinuxA-CView Answer on Stackoverflow
Solution 4 - LinuxRichardView Answer on Stackoverflow