24

I'm trying to cat a bunch of files, some of which may not exist. Now that's ok if some of them don't exist, but I don't want cat to return an error in this case, if possible. Here's my call:

zcat *_max.rpt.gz *_min.rpt.gz | gzip > temp.rpt.gz

When this command is run, either a bunch of files matching *_max.rpt.gz will exist, or *_min.rpt.gz will exist. If the other doesn't exist, I don't care, I just want to concatenate what I can. But I'm getting an error message which stops the rest of my code from running.

Anything I can do? Thanks.

JDS
  • 16,388
  • 47
  • 161
  • 224

5 Answers5

36

Just redirect the stderr to /dev/null:

cat file1 file2 .... 2>/dev/null

If one or more files don't exist, then cat will give an error which will go to /dev/null and you'll get the desired result.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • my man... I knew people used /dev/null for something. EDIT - not sure where to put 2>/dev/null in my line of code - after the pipe or before? – JDS Oct 10 '12 at 22:08
  • 1
    @YoungMoney Before the pipe: `zcat *_max.rpt.gz *_min.rpt.gz 2>/dev/null | gzip > temp.rpt.gz` – P.P Oct 10 '12 at 22:11
  • 15
    `cat` will return a **non-zero exit code** if it can't find one of the input files. – rustyx Oct 16 '18 at 08:57
11

[ -f file.txt ] && cat file.txt

user3167916
  • 239
  • 3
  • 4
8
grep -hs ^ file1 file2 ....

Unlike cat has zero return code. Option -h disables file name print, option -s disables file error reporting, ^ matches all lines.

wass rubleff
  • 326
  • 1
  • 14
orgoj
  • 191
  • 1
  • 3
5

You can append || True to your commands to silence the exit code.

DustWolf
  • 516
  • 7
  • 10
1
zcat `ls *.rpt.gz | grep -E '_(max|min)\.rpt\.gz$'` | gzip > temp.rpt.gz

Bit of a hack, but then so is the shell :-P

j_random_hacker
  • 50,331
  • 10
  • 105
  • 169