我的linux命令是
cat /etc/myfile.txt > newfile.txt
我的问题是如何检查文件/etc/myfile.txt是否为空并保存
一个命令行中的文件
你可以使用bash
中的条件表达式来检查文件是否存在(-f
标志),而不是用-s
标志清空。
你也可以使用cp
创建一个新的文件副本而不是cat
-ing它。
if [[ -f /etc/myfile.txt && -s /etc/myfile.txt ]]; then
cp /etc/myfile.txt newfile.txt
fi
不知道为什么你会打扰使用单行而不是正确的可读示例。无论如何,你可以使用上面的逻辑
[[ -f /etc/myfile.txt && -s /etc/myfile.txt ]] && cp /etc/myfile.txt newfile.txt
[ -s "/etc/myfile.txt" ] && cat /etc/myfile.txt > newfile.txt
你没有cat
文件,而是使用cp
。
这里,-s
选项检查文件的大小是否为非零。来自Linux盒子上的man test
,
-s FILE
FILE exists and has a size greater than zero
编辑:如果/etc/myfile.txt
是一个常规文件,上述解决方案就足够了。如果要在检查non-zero
大小之前检查它是否是常规文件,则需要-f
标志
[[ -f "/etc/myfile.txt" && -s "/etc/myfile.txt" ]] && cp /etc/myfile.txt newfile.txt