How to suppress error message of a command?

前端 未结 3 1541
梦谈多话
梦谈多话 2020-12-05 06:26

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 e

相关标签:
3条回答
  • 2020-12-05 06:58

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

    ls *.zip 2> /dev/null
    
    0 讨论(0)
  • 2020-12-05 07:00
    $ 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.

    0 讨论(0)
  • 2020-12-05 07:10

    To suppress error message and also return 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
    
    0 讨论(0)
提交回复
热议问题