• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

bash的检查,如果文件夹有内容

用户头像
it1352
帮助1

问题说明

我试图创建一个bash脚本,将删除我的 .waste 目录中的一切。我有我写了一个基本的脚本,但我想它首先检查 .waste 目录中有内容,如果有的话,呼应出一个简单的 文件夹已空的!消息。我不是太精明关于如果如果别人声明,我不知道是什么 [] 公式我需要把检查presence。

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 [ ] equation I'd need to put in to check for presence.

基本code:

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

任何帮助将是AP preciated!

Any help would be appreciated!

(PS不知道星号是在最后正确的,我也尝试用它的脚本,我记得它删除了目录中的一切以及)

(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)

正确答案

#1

您可以检查一个目录是空的是这样的:

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

找到命令将打印并退出发现里面的第一个文件或目录$目标之后。在的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.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfiggf
系列文章
更多 icon
同类精品
更多 icon
继续加载