当源文件不存在时,使用cat命令避免出错。

5

我想使用Linux命令将文件1的内容复制到文件2中。

cat file1 > file2

根据程序运行的不同环境,文件1可能存在或不存在。如果文件1不存在应该在命令中添加什么以便不返回错误?我读到过追加2>/dev/null不会出错。尽管如此,当file1不存在时,命令

cat file1 2>/dev/null > file2 让文件2的先前内容完全丢失了。我不希望在文件1不存在时丢失文件2的内容,也不希望返回错误。

同时,请问还有哪些情况下该命令会执行失败并返回错误?

4个回答

11

首先测试file1文件。

[ -r file1 ] && cat ...

查看 help test 以获取详细信息。


好的,这是完美的竞争条件。 - hek2mgl
@hek2mgl,请解释一下它如何导致竞态条件,它会破坏我的代码吗?我应该使用什么替代方案? - John Doe
问题在于,在检查文件和实际创建文件之间,可能会有其他进程进入 CPU 并创建或删除文件。另一种选择是我发布的解决方案:https://dev59.com/nqbja4cB1Zd3GeqPi5uQ#47197501 - hek2mgl

0

对 @Ignacio Vazquez-Abrams 进行详细阐述:

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

0

首先,你写道:

我正在尝试使用Linux命令将file1的内容复制到file2中

要将file1的内容复制到file2中,请使用cp命令:

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

仅为完整起见,使用cat

我会将stderr重定向到/dev/null并检查返回值:

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

0
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

这是在 file1 不存在的情况下,而不是空的情况下。 - John Doe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接