如何检查文件夹中是否包含内容? [英] How do I check if a folder has contents?
问题描述
我正在尝试创建一个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
offind
rather than its own exit code directly is that there's no way to make thefind
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 offind
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屋!
- Redirect
- 重定向