Bash检查文件夹是否有内容 [英] Bash checking if folder has contents

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

问题描述

我正在尝试创建一个Bash脚本,它将删除我的 .waste 目录中的所有内容。我有一个我写的基本脚本,但是我想要首先检查 .waste 目录是否具有内容,如果是,回显一个简单的 文件夹已经空了!消息。对于如果 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/*

(PS不知道星号在最后是否正确,该脚本与它,我记得它删除了 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)

推荐答案

您可以检查目录是否为空,如下所示:

You can check if a directory is empty like this:

#!/bin/sh
target=$1
test "$(ls -A "$target" 2>/dev/null)" || echo The directory $target is empty

还是更好:

#!/bin/sh
target=$1
if test "$(ls -A "$target")"; then
    echo not empty, do something
else
    echo The directory $target is empty '(or non-existent)'
fi



更新



如果目录包含很多文件,这可能很慢。在这种情况下,这应该更快:

UPDATE

If the directory contains many files, this can be slow. In that case, this should be faster:

#!/bin/sh
target=$1
if find "$target" -mindepth 1 -print -quit | grep -q .; then
    echo not empty, do something
else
    echo The directory $target is empty '(or non-existent)'
fi

find 命令将打印并退出后,找到第一个文件或目录 $目标 grep -q。只有在找到打印任何东西时才会退出,换句话说,如果有文件。

The find command will print and quit after it finds the first file or directory inside $target. The grep -q . will exit with success only if the find printed anything, in other words, if there were any files.

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

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