How can I suppress error messages of a command?
LinuxBashLinux 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