shell脚本输入目录,检测非空,进行循环

要求用户输入目录,判断如果目录不存在,则创建目录,作为变量
如果目录存在,且为空,则什么都不做,作为变量
如果目录存在,但不为空,进行提示,用户可以选择清空目录,此目录作为变量,也可
以选择不清空,让用户再次输入,回到开头再次判断。

刚开始学编程,循环控制不太懂,请教了

第1个回答  2012-08-10
写个大概吧
#!/bin/bash
while ;
do
read -p "请输入你要查询的目录,注意需要用绝对路径" a
if [ -d ${a} ]
then echo “目录存在"
num= `ll -a $a | wc -l` %> /dev/null
if [ ${num} -eq 0 ]
then echo "目录为空"
esle read -p "目录非空,是否清空目录,清空请按y,不清空按n" b
if [ "${b}" == "y" ]
then rm -rf ${a}\/*
fi
fi
else echo "目录不存在"
fi
done

没测试 可能有点小错误 大概是这个样子的
第2个回答  2012-08-10
#!/bin/bash
while :
do
read -p "Please enter a path: " dir
[ -d $dir ] || (mkdir -p $dir; exit)
if [ "`ls -A $dir`" == "" ]; then
exit
else
read -p "$dir is not empty, do you want clear it? [yes/no] " choice
if [ "$choice" == "yes" ];then
rm -rf $dir/*
exit
elif [ "$choice" == "no" ];then
continue
fi
fi
done本回答被网友采纳
第3个回答  2012-08-10
#直接手写上去的,未经测试,不保证一定运行正确,但逻辑是正确的
#!/bin/bash

exit_flag="N"

while [ "${exit_flag}" = "N" ]
do
echo -n "input directory:"
read line
tmp_dir=${line}

if [ -d ${tmp_dir} ]
then
cnt="`cd ${tmp_dir} | ls -a | wc -l`"
if [ $cnt -gt 0 ]
then
echo -n "directory [${tmp_dir}] is not empty ,clear files (Y/N):"
read cls_flag
if [ "${cls_flag}x" == "Yx" -o "${cls_flag}x" == "yx" ]
then
cd ${tmp_dir} && rm -fr *
exit_flag="Y"
else
exit_flag="N"
fi
else
mkdir -p ${tmp_dir}
exit_flag="Y"
fi
done
第4个回答  推荐于2016-02-18
#!/usr/bin/env bash
#--------Get current project's directory(path)-----------------#
#path:$Path
Path=`dirname "$0"`
Path=`cd "$Path";pwd`
#-------Get current project's directory(path)------------------#
#----------------------function input your path---------------------#
mydir=
input_dir(){
echo Please input your path \(like:${Path}\):
read inputpath
if test -d ${inputpath};then
echo "your input path is a directory."
num=`ls -a ${inputpath} | wc -l`
if [ $num -gt 2 ];then
echo "your input path is not a empty directory."
echo Do you want to \clear this directory\(dir:${inputpath}\)[Y/N]?
read answer
case "$answer" in
[Yy]*)
mydir=`cd ${inputpath};pwd`
for item in $(ls ${inputpath})
do
echo rm -rfR ${inputpath}/$item
rm -rfR ${inputpath}/$item
done
;;
*)
input_dir
;;
esac
else
echo "your input path is a empty directory."
fi
else
mkdir ${inputpath}
mydir=`cd ${inputpath};pwd`
fi
}
#----------------------function input your path---------------------#
#Run here
input_dir本回答被提问者采纳

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网