Unix确定文件是否为空

时间:2015-03-03 02:24:01

标签: unix if-statement command-line-arguments

我正在尝试创建一个脚本来检查文件中是否有任何tyext。我开发了以下脚本。我已经检查了是否有2个参数,看看文件是否存在,但是我在检查文件中是否存在文本时遇到问题。代码如下:

#!/bin/ksh
#check if number of arguments are 2

if [ $# -ne 2 ]; then
    echo "Does not equal two arguments"
    echo "Usage $0 inputfile outputfile"
    exit 1
fi

#check if input file exists

if [ ! -f $1 ]; then
    echo "$1 not found!"
    exit 1
fi

#Check if input file is null
#This next block of code is where the issue is
if [ grep -q $1 -eq 0 ]; then
    echo "$1 must have text within the file"
    exit 1
fi

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

测试" -s"选项检查文件是否为空 - 请参阅manual。所以你的最后一块将成为

#Check if input file is null
#This next block of code is where the issue is
if [ ! -s $1 ]; then
    echo "$1 must have text within the file"
    exit 1
fi

答案 1 :(得分:0)

尝试使用stat

stat -c%s filename