awkOut1="awkOut1.csv"
awkOut2="awkOut2.csv"
if [[ "$(-s $awkOut1)" || "$(-s $awkOut2)" ]]
上面的'if'检查shell脚本给了我以下错误:
-bash: -s: command not found
有人建议吗?
答案 0 :(得分:2)
如果您只有2个文件,我会做
if [[ -e "$awkOut1" && ! -s "$awkOut1" ]] &&
[[ -e "$awkOut2" && ! -s "$awkOut2" ]]
then
echo both files exist and are empty
fi
由于[[
是命令,因此可以将退出状态与&&
链接在一起,以确保它们都是真实的。另外,在[[
(但不能在[
中)中,您可以使用&&
将测试链接在一起。
请注意-s测试True if file exists and is not empty.
,因此我明确添加-e测试,以便-s仅检查文件是否为空。
如果您拥有超过2个:
files=( awkOut1.csv awkOut2.csv ... )
sum=$( stat -c '%s' "${files[@]}" | awk '{sum += $1} END {print sum}' )
if (( sum == 0 )); then
echo all the files are empty
fi
此文件不测试文件是否存在。
答案 1 :(得分:1)
您可以使用基本的Bourne shell语法和test
命令(左括号)来确定两个文件是否为非空:
if [ -s "$awkOut1" -o -s "$awkOut2" ]; then
echo "One of the files is non-empty."
fi
在使用单括号时,-o
的意思是“或”,因此该表达式将检查awkOut1或awkOut2是否为非空。
如果您有一个充满文件的整个目录,并且想要找出其中是否有空,则可以执行以下操作(同样使用基本的Bourne语法和标准实用程序):
find . -empty | grep -q . && echo "some are empty" || echo "no file is empty"
在这一行中,find
将打印当前目录中(以及递归地在任何子目录中)为空的所有文件; grep
会将其变为退出状态;然后您可以根据成功或失败找到空容器采取措施。在if
语句中,看起来像这样:
if find . -empty | grep -q .; then
echo "some are empty"
else
echo "no file is empty"
fi
答案 2 :(得分:0)
这里是GNU awk和filefuncs extension的一个。它检查所有给定参数的文件,并在第一个为空时退出:
$ touch foo
$ awk '
@load "filefuncs" # enable
END {
for(i=1;i<ARGC;i++) { # all given files
if(stat(ARGV[i], fdata)<0) { # use stat
printf("could not stat %s: %s\n", # nonexists n exits
ARGV[i], ERRNO) > "/dev/stderr"
exit 1
}
if(fdata["size"]==0) { # file size check
printf("%s is empty\n",
ARGV[i]) > "/dev/stderr"
exit 2
}
}
exit
}' foo
输出:
foo is empty