当 src 文件不存在时避免 cat 命令出错

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

我正在尝试使用 linux 命令将文件 1 的内容复制到文件 2

cat file1 > file2

file1 可能可用也可能不可用,这取决于程序运行的不同环境 运行。如果 file1 不可用,应该向命令添加什么,这样它就不会 return 出错?我读过附加 2>/dev/null 不会出错。虽然这是真的,但我没有收到命令

的错误

cat file1 2>/dev/null > file2 当 file1 不存在时,使 file2 的先前内容完全为空。我不想丢失 file2 的内容以防 file1 不存在并且不想 return.

出现错误

还有哪些其他情况下命令会失败并且 return 出错?

首先测试 file1

[ -r file1 ] && cat ...

详情见help test

详述@Ignacio Vazquez-Abrams :

if (test -a file1); then cat file1 > file2; fi
File1 is empty

File2 consists below content
praveen

Now I am trying to append the content of file1 to file2

Since file1 is empty to nullifying error using /dev/null so output will not show any error

cat file1 >>file 2>/dev/null

File2 content not got deleted

file2 content exsists
praveen 

If [ -f file1 ]
then
cat file  >> file2
else
cat file1 >>file 2>/dev/null
fi

首先,您写道:

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

要将文件 1 的内容复制到文件 2,请使用 cp 命令:

if ! cp file1 file2 2>/dev/null ; then
    echo "file1 does not exist or isn't readable"
fi

为了完整起见,cat:

我会将 stderr 通过管道传输到 /dev/null 并检查 return 值:

if ! cat file1 2>/dev/null > file2 ; then
    rm file2
    echo "file1 does not exist or isn't readable"
fi