如何检查文件夹中是否包含内容? [英] How do I check if a folder has contents?

查看:43
本文介绍了如何检查文件夹中是否包含内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个Bash脚本,该脚本将删除 .waste 目录中的所有内容.我有一个基本的脚本,但是我希望它首先检查 .waste 目录中是否包含内容,如果有,则回显一个简单的文件夹已为空!" 消息.我不太了解 if if else 语句,而且我不知道 [] 等式需要检查什么

I'm trying to create a Bash script that will delete everything in my .waste directory. I have a basic script I wrote but I want it to first check if the .waste directory has contents, and if so, to echo out a simple "Folder already empty!" message. I'm not too savvy about if and if else statements, and I don't know what the [ ] equation needs to check for presence.

基本代码:

#! /bin/bash
echo "The files have been deleted:"
cd /home/user/bin/.waste/
ls
rm -rf /home/user/bin/.waste/*

(P.S.不确定星号最后是否正确,我确实尝试过使用该脚本,并且我还记得它也删除了 bin 目录中的所有内容)

(P.S. not sure if the asterisk is correct at the end, I did try the script with it and I recall it deleted everything in the bin directory as well)

推荐答案

您可以使用 find 并处理其输出来检查目录是否为空:

You can check if a directory is empty using find, and processing its output:

#!/bin/sh
target=$1
if find "$target" -mindepth 1 -print -quit 2>/dev/null | grep -q .; then
    echo "Not empty, do something"
else
    echo "Target '$target' is empty or not a directory"
fi

也就是说:

  • 使用 find $ target ( -mindepth 1 )下找到第一个文件系统条目,然后打印( -print ),然后停止处理(-退出)
    • 重定向 stderr 以抑制任何错误消息(=噪音)
    • Use find to find the first filesystem entry under $target (-mindepth 1), print it (-print), and stop processing (-quit)
      • Redirect stderr to suppress any error messages (= noise)
      • grep -q.将在处理最多一个字符后退出.如果看到一个字符,则成功退出;如果没有(输入为空),则退出失败.
      • grep -q . will exit after processing at most one character. If it sees a character it exits with success, if it doesn't (its input is empty) then it exits with failure.

      我们不得不依赖 find stdout 而不是直接自己退出代码的原因是,没有办法使 find 命令在发现或未发现文件的情况下使用可区分的退出代码.

      The reason we have to rely on the stdout of find rather than its own exit code directly is that there's no way to make the find command use distinguishable exit codes in case files were found or not.

      代替传递给 grep -q 的方法,另一种替代方法是捕获 find 的输出并检查其是否为空字符串.

      Instead of piping to grep -q, another alternative would be to capture the output of find and check if it's an empty string or not.

      #!/bin/sh
      target=$1
      if [ "$(find "$target" -mindepth 1 -print -quit 2>/dev/null)" ]; then
          echo "Not empty, do something"
      else
          echo "Target '$target' is empty or not a directory"
      fi
      

      这样捕获命令输出使用了一个子外壳.我认为使用 grep 的解决方案可能更快,但是我还没有测试.

      Capturing command output like this uses a sub-shell. I think the solution using grep is probably faster, but I haven't tested it.

      这篇关于如何检查文件夹中是否包含内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆