Linux shell脚本学习课后作业

课后作业


问题描述

编写shell脚本,实现功能:依次判断当前目录下是否有temp1(2,…,10).txt文件。若有,则打印已经存在,并输出里面的内容;若没有,则创建,并提示已经创建了这个文件。创建结束后,依次删除这些文件。

用到的知识点

  • shell脚本编写
  • 循环语句
  • 新建文件
  • 查询文件
  • 打印提示信息
  • 文件删除

代码实现

#!/bin/bash
echo -e "********Starting*******"
read -p "Please input a number:" nu 
for(( i=1;i<=$nu;i=i+1 ))
do
    if [ -e "tmp"${i}".txt" ]; then
        echo -e "File exits:"tmp"${i}".txt""
        touch "tmp"${i}".txt"
    else
        touch "tmp"${i}".txt"
        echo ""tmp"${i}".txt" has been created!"
    fi
done

echo "All files have been created!"

for(( i=1;i<=$nu;i=i+1 ))
do
    rm -rf "tmp"${i}".txt"
    echo ""tmp"${i}".txt" has been removed!"
done

echo "All files have been removed!"
exit 0

运行结果

***Starting**
Please input a number:10
File exits:tmp1.txt
tmp2.txt has been created!
tmp3.txt has been created!
tmp4.txt has been created!
tmp5.txt has been created!
tmp6.txt has been created!
tmp7.txt has been created!
tmp8.txt has been created!
tmp9.txt has been created!
tmp10.txt has been created!
All files have been created!
tmp1.txt has been removed!
tmp2.txt has been removed!
tmp3.txt has been removed!
tmp4.txt has been removed!
tmp5.txt has been removed!
tmp6.txt has been removed!
tmp7.txt has been removed!
tmp8.txt has been removed!
tmp9.txt has been removed!
tmp10.txt has been removed!
All files have been removed!

猜你喜欢

转载自blog.csdn.net/cherry593/article/details/81780411