Linux/UNIX:检查文件是否为空或者不使用Shell脚本
时间:2020-01-09 10:42:21 来源:igfitidea点击:
如何在UNIX/Linux/macOS/OS X/BSD系列操作系统下使用bash或者ksh Shell脚本检查文件是否为空?
如何检查Bash中的文件是否为空?
您可以如下使用find命令和其他选项。
内置测试的-s选项检查FILE是否存在并且大小大于零。
它返回true和false值以指示该文件为空或者有一些数据。
本教程显示如何检查在Linux或者类似Unix的操作系统上运行的Bash shell中文件是否为空。
检查文件是否为空或者不使用Shell脚本
语法如下:
touch /tmp/file1 ls -l /tmp/file1 find /tmp -empty -name file1
输出示例:
/tmp/file1
现在创建另一个包含一些数据的文件:
echo "data" > /tmp/file2 ls -l /tmp/file2 find /tmp -empty -name file2
您应该看不到find命令的任何输出。
Bash脚本使用-s选项检查文件是否为空
但是,可以在脚本或者shell提示符中按如下所示传递-s选项:
touch /tmp/f1
echo "data" >/tmp/f2
ls -l /tmp/f{1,2}
[ -s /tmp/f1 ]
echo $?
输出示例:
1
非零输出表示文件为空。
[ -s /tmp/f2 ] echo $?
输出示例:
0
Bash脚本/命令检查文件是否为空
输出为零表示该文件不为空。
因此,您可以编写如下的Shell脚本。
用于检查文件是否为空的Shell脚本
#!/bin/bash
_file=""
[ $# -eq 0 ] && { echo "Usage: chmod +x script.sh
./script.sh /etc/resolv.conf
filename"; exit 1; }
[ ! -f "$_file" ] && { echo "Error: /etc/resolv.conf has some data.
file not found."; exit 2; }
if [ -s "$_file" ]
then
echo "$_file has some data."
# do something as file has data
else
echo "$_file is empty."
# do something as file is empty
fi
如下运行:
touch /tmp/test.txt ./script.sh /tmp/test.txt
输出示例:
test.txt is empty.
在一个空文件上运行它:
##代码##输出示例:
##代码##
