判断文件或目录是否存在,文件大小是否为0

1、想要判断目录dir1是否存在,可以使用 [ -d 目录路径 ] 的方式进行判断,下面示例:

if [ -d 'dir/data1' ] && [ -d 'dir/data2' ]; then
  echo "Both dir/data1and dir/data2exist in 'dir'"
  # 在这里执行你想要的操作
elif [ -d 'dir/data1' ]; then
  echo "Only data1 exists in 'dir'"
  # 在这里执行你想要的操作
elif [ -d 'dir/data2' ]; then
  echo "Only data2 exists in 'dir'"
  # 在这里执行你想要的操作
else
  echo "Both data1 and data2 do not exist in 'dir'"
  # 在这里执行你想要的操作
fi

2、如果想要在Shell脚本中判断目录 'dir' 下是否存在文件 'file1' 和 'file2',可以使用[ -f 文件路径 ] 的方式分别判断每个文件是否存在。以下是一个示例脚本代码,用于判断并执行相应操作:

if [ -f 'dir/file1' ] && [ -f 'dir/file2' ]; then
  echo "Both file1 and file2 exist in 'dir'"
  # 在这里执行你想要的操作
elif [ -f 'dir/file1' ]; then
  echo "Only file1 exists in 'dir'"
  # 在这里执行你想要的操作
elif [ -f 'dir/file2' ]; then
  echo "Only file2 exists in 'dir'"
  # 在这里执行你想要的操作
else
  echo "Both file1 and file2 do not exist in 'dir'"
  # 在这里执行你想要的操作
fi

在这个示例中,首先使用 [ -f 'dir/file1' ] 检查 'dir/file1' 是否存在,然后使用 [ -f 'dir/file2' ] 检查 'dir/file2' 是否存在。根据存在与否的不同情况,可以编写适当的代码块来执行相应的操作。

3、判断文件是否为空,使用 [ -s 'dir/file ] 检查 ’dir/file'文件是否为空,当被检查文件大小不为0时返回true,下面示例:

#判断file是否是空文件
if [ -s "./file" ]; then
   echo "Then file is not blank"
else 
   echo "Then file is blank"
   exit 1
fi

exit 1表示当文件为空时,退出该脚本

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值