bash的检查,如果文件夹中有内容 [英] Bash checking if folder has contents
问题描述
我试图创建一个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)
推荐答案
您可以检查一个目录是空的是这样的:
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.
这篇关于bash的检查,如果文件夹中有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!