Linux shell编程作业

作业1

编写脚本exe1,该脚本接收一个命令行参数,并根据其类型做以下操作:

  1. 若参数为普通文件,则显示其内容
  2. 若参数为压缩文件,则解压缩(如同目录下有同名文件则放弃)
  3. 若参数为目录,则将其归档并压缩(如已有同名压缩文件则放弃)
  4. 若参数不存在,给出错误提示并退出
#!/bin/bash

str=$1
len=${#str}
let len=$len-3

if [ -e $1 ]
then
        if [ -f $1 ]
        then
                if [ ${str:$len:3} = ".gz" ]
                then
                        gzip -d $1
                else
                        cat $1
                fi
        elif [ -d $1 ]
        then
                file=$1".tar.gz"
                if [ ! -e $file ]
                then
                        tar -czvf $file $1
                fi
        fi

else
        echo "No such file! Error!"
fi

注意:

  1. test语句的空格
  2. 引用参数要写$
  3. 整数计算,要用let操作
  4. 用{}进行的变量操作不需要$引用,只需要写变量名
  5. elif也要加then

作业2

编写脚本exe2,由用户输入一组数(以end表示输入结束),输出这些数的和,结果保留2位小数。要求使用函数做输入类型检查,并给出错误提示信息。

#!/bin/bash

if_is_legal(){
    
    
        if  [[ $1 = [0-9]*\.[0-9]* ]] || [[ $1 = [0-9]*[^.a-zA-Z]  ]] || [[ $1  = [0-9] ]]
        then
                return 0
        else
                return 1
        fi
}
read num
sum=0

while [ $num != "end" ]
do
        if  if_is_legal $num
        then
                sum=$(echo "$sum+$num" | bc)
        else
                echo "type error! please input again!"
        fi
        read num
done
echo "scale=2;$sum/1.0" |bc

注意:

  1. 函数如何传参
  2. 函数返回值的写法
  3. 浮点运算的写法

作业3

编写脚本exe3,该脚本对比两个目录dir1和dir2(通过参数给出),将dir2中符合下列条件的文件复制到dir1,并将每一条复制记录存储到文件record中:

  1. 该文件不在dir1中
  2. 该文件比dir1中的同名文件更新
#!/bin/bash

for item in `ls $2`
do
        echo $item
        if [ -e $1"/"$item ]
        then
                if [ $2"/"$item -nt $1"/"$item ]
                then
                        cp $2"/"$item $1
                        echo "replace $item in $1" >> record
                fi
        else
                cp $2"/"$item $1
                echo "copy $item from $2 to $1" >> record
        fi
done
echo "done successfully!"

注意:

  1. 文件名的拼接
  2. for循环的使用

猜你喜欢

转载自blog.csdn.net/DwenKing/article/details/109406982