如何在 Bash 脚本中根据输入字符串删除子目录或创建文件?-灵析社区

MaxClick

写一个脚本,任意输入一个目录和一个字符串,对输入的字符串进行判断,如果字符串内容等于”ww”,则将该目录下的所有子目录删除,所有子文件拷贝到/var 目录下:如果字符串内容等于”rr”,则在该目录下创建 test1.txt 文件 #!/bin/bash if [ x$1 == x ] then read -p "请输入一个目录:" dir else dir=$1 fi read -p "请输入一个字符串:" str1 echo $str1","$dir if [ -d $dir ] then case $str1 in "ww") for file in `ls $dir` do file_path=$dir/$file if test -f $file_path then cp $file_path /var elif test -d $file_path then rm -rf $file_path fi done ;; "rr") cd $dir &&`touch test1.txt` ;; *) echo "未知的输入,请输入rr或ww..." ;; esac else echo "请输入一个目录..." fi

阅读量:206

点赞量:0

问AI
看是否符合。 #!/bin/bash # 检查是否提供了目录作为参数 if [ -z "$1" ]; then read -p "请输入一个目录: " dir else dir="$1" fi # 读取用户输入的字符串 read -p "请输入一个字符串: " str1 # 打印出输入的字符串和目录 echo "$str1,$dir" # 检查目录是否存在 if [ -d "$dir" ]; then case "$str1" in "ww") # 遍历目录下的所有文件和子目录 for file in "$dir"/*; do file_path="$file" if [ -f "$file_path" ]; then # 如果是文件,则拷贝到/var目录 cp "$file_path" /var/ elif [ -d "$file_path" ]; then # 如果是子目录,则删除它 rm -rf "$file_path" fi done ;; "rr") # 如果是"rr",则在目录中创建test1.txt文件 touch "$dir/test1.txt" ;; *) echo "未知的输入,请输入rr或ww..." ;; esac else echo "请输入一个存在的目录..." fi