我们在平常工作中,你是否感觉shell脚本只是命令的堆砌;很多时候只是为了实现功能而没有好的组织结构;自己的脚本都不想再看一遍;此让你的shell脚本有python一样的美感并且极易维护,真的是shell脚本写到停不下来。
现以k8s发版脚本为例,看一下脚本的优化过程:
#!/bin/bash set -eu ns=$1 project_name=$(echo $2|awk -F '_' '{print $2}') modul_name=$(echo $2|awk -F '_' '{print $3}') image_tag=harbor.example.cn:32443/jenkins-$ns/$project_name/$modul_name:$ns_$(date +%y%m%d%H%M)_manual_$project_name_$modul_name # 1. 构建镜像 docker build -t $image_tag -f jarFile . # 2. 检查镜像 result=$(docker images|grep $tag) if [[ $result == '' ]]; then echo "镜像不存在,请检查!" exit 1 fi # 3. 上传镜像然后删除本地镜像 docker push $image_tag && docker rmi $image_tag # 4. 更新deployment镜像 kubectl patch deployment $ns-$project_name-$modul_name -n $ns --patch "{\"spec\": {\"template\": {\"spec\": {\"containers\": [{\"name\": \"$ns-$project_name-$modul_name\",\"image\":\"$image_tag\"}]}}}}"
其实我这个脚本因为功能不是很多,所以看起来还算清晰。但要是那种上百行从上到下的shell脚本,那要理清楚逻辑就是很痛苦的事情了。