如何检查文件夹是否有内容? [英] 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
),并停止处理 (-quit
)- 重定向
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
- 重定向