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



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

cat file1 > file2

file1 可能可用,也可能不可用,具体取决于运行程序的不同环境。如果 file1 不可用,应该向命令中添加什么,以便它不会返回错误?我已经读到附加 2>/dev/null 不会出错。虽然这是真的,但我没有收到错误命令

cat file1 2>/dev/null > file2当文件1不存在时,使File2以前的内容完全为空。我不想丢失 file2 的内容,以防 file2 不存在并且不希望返回错误。

另外,在哪些其他情况下,命令会失败并返回错误?

首先测试file1

[ -r file1 ] && cat ...

有关详细信息,请参阅help test

详细阐述了@Ignacio巴斯克斯-艾布拉姆斯:

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

首先,你写道:

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

要将 file1 的内容复制到文件 2,请使用 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

最新更新