好的,我正在编写一个shell脚本来删除一个目录,但只有在里面没有文件的情况下.
我想要做的是有一个if语句,它将检查目录中是否有文件,是否有文件询问用户是否要先删除文件然后删除目录.
我已经看了很多,并找到了一种方法来检查目录中是否存在文件,但我无法让它超过该阶段.
这是我到目前为止创建的if语句,用于检查目录中是否存在文件:
echo "Please type the name of the directory you wish to remove "
read dName
shopt -s nullglob
shopt -s dotglob
directory=$Dname
if [ ${#directory[@]} -gt 0 ];
then
echo "There are files in this directory! ";
else
echo "This directory is ok to delete! "
fi
;;
Run Code Online (Sandbox Code Playgroud)
你不需要检查; rmdir
只会删除空目录.
$ mkdir foo
$ touch foo/bar
$ rmdir foo
rmdir: foo: Directory not empty
$ rm foo/bar
$ rmdir foo
$ ls foo
ls: foo: No such file or directory
Run Code Online (Sandbox Code Playgroud)
在更实际的设置中,您可以使用rmdir
带有if
语句的命令来询问用户是否要删除所有内容.
if ! rmdir foo 2> /dev/null; then
echo "foo contains the following files:"
ls foo/
read -p "Delete them all? [y/n]" answer
if [[ $answer = [yY] ]]; then
rm -rf foo
fi
fi
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3007 次 |
最近记录: |