Search code examples
shellunixcut

How to ignore "can't open file" error message in unix


I am searching table name in all scripts across the directories in specific directory. eg. home/abcd

I have abc, pqr, xyz directory under home/abcd. I have my project specific scripts inside these directories.

I have used the command like this.

grep table_name home/abcd/abc | cut -d":" -f1 > output.txt

Here, whenever the file under this directory don't have READ permission, I am getting an error message like this:

Can't open the file.

But, I don't want to show this message on the screen.


Solution

  • Use 2>/dev/null so that stderr will not appear:

    grep table_name home/abcd/abc 2>/dev/null | cut -d":" -f1 > output.txt
    

    Test

    $ ls -ltr a*
    -rwxr-xr-x 1 me me 24 Oct  9 14:06 a
    --wx-wx-wx 1 me me  0 Oct  9 14:10 a1 <--- no reading rights
    $ grep a a*
    a:123 abc
    grep: a1: Permission denied
    $ 
    $ grep a a* 2>/dev/null
    a:123 abc