Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid error with cat command when src file doesn't exist

I am trying to copy content of file1 to file 2 using linux command

cat file1 > file2

file1 may or may not be available depending on different environments where the program is being run. What should be added to the command in case file1 is not available so that it doesn't return an error ? I have read that appending 2>/dev/null will not give error. While that's true, and I didn't get an error the command

cat file1 2>/dev/null > file2 made file2's previous content completely empty when file1 wasn't there. I don't want to lose the content of file2 in case file1 wasn't there and don't want an error to return.

Also in what other cases can the command fail and return an error ?

like image 581
John Doe Avatar asked Jan 03 '23 05:01

John Doe


1 Answers

Test for file1 first.

[ -r file1 ] && cat ...

See help test for details.

like image 102
Ignacio Vazquez-Abrams Avatar answered Jan 08 '23 07:01

Ignacio Vazquez-Abrams