好的,所以我正在编写一个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
;;
答案 0 :(得分:6)
你不需要检查; 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
在更实际的设置中,您可以使用带有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
答案 1 :(得分:1)
感觉就像你在使用的语法中混合了一些语言。对脚本进行微小的更改,你可以使用bash globing来查看它是否已经完整(也可以创建一个数组,但是看不太合理),尽管我可能仍会使用与{{3}类似的东西并让rmdir
处理错误检查。
#!/bin/bash
echo "Please type the name of the directory you wish to remove "
read dName
[[ ! -d $dName ]] && echo "$dName is not a directory" >&2 && exit 1
shopt -s nullglob
shopt -s dotglob
found=
for i in "$dName"/*; do
found=: && break
done
[[ -n $found ]] && echo 'There are files in this directory!' || echo 'This directory is ok to delete!'
请注意原始语法中的几个错误:
$dName
不等于$Dname
(如果它们有空格或其他特殊字符,您应该引用变量名称)directory
不是数组,您可以通过directory=($Dname/*)
!
将尝试使用双引号执行历史记录扩展。