bash的检查,如果文件夹有内容
问题说明
我试图创建一个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.
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcfiggf
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20