shell 练习

1. 备份并压缩 /etc 下所有内容到 /root/bak,存放形式为 2020_2_15_etc.tar.bz2。

#!/bin/bash

DestPath=/root/bak
Date=$(date +%Y_%m_%d)

[ -d ${DestPath} ] || mkdir -p ${DestPath}

cd /etc
tar cjf ${DestPath}/${Date}.tar.bz2 *
cd -

 2. 查看内存占用率,如果大于80%则报警

#!/bin/bash

Use=$(free | awk ‘/^Mem/{print $3/$2*100}‘)
[ ${Use%.*} -gt 80 ] && echo "warning" || echo "ok"

注意整数比大小用 -gt,字符串用 >=

3. 

#!/bin/bash

string="Bash is an excellent excellent programming language language"
echo "${string}"
cat << eof
1] get the length of string     
2] delete all language
3] replace first excellent with best
4] replace all excellent with best
eof
read -p "please input [1|2|3|4] : "  var
case $var in
        1)
                echo $(echo ${string} | wc -c)
                ;;
        2)
                echo ${string//language/}
                ;;
        3)
                echo ${string/excellent/best}
                ;;
        4)
                echo ${string//excellent/best}
                ;;
        *)
                ;;
esac

相关推荐