JDS
JDS

Reputation: 16998

unix cat multiple files - don't cause error if one doesn't exist?

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.

Upvotes: 27

Views: 25049

Answers (5)

user3167916
user3167916

Reputation: 299

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

Upvotes: 16

DustWolf
DustWolf

Reputation: 585

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

Upvotes: 6

orgoj
orgoj

Reputation: 200

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.

Upvotes: 9

j_random_hacker
j_random_hacker

Reputation: 51246

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

Upvotes: 1

P.P
P.P

Reputation: 121407

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.

Upvotes: 38

Related Questions