作为一个新世纪的程序员,尤其是后端程序员,经常会接触到Linux服务器。并做一些发布、部署、运维、问题排查等工作,这个时候就会用到shell命令。
但今天讲的主要是主要是devops相关的shell脚本文件的编写。
先放一个简单的demo
#!/bin/bash
DEVSTACK="$(pwd)"
if [[ -z "${DEVSTACK_WORKSPACE}" ]]; then
echo "set workspace dir to default"
cd ..
DEVSTACK_WORKSPACE="$(pwd)"
else
cd ${DEVSTACK_WORKSPACE}
fi
## include conf file
source ${DEVSTACK}/common-conf.sh
code_dir=$2
app=$3
app_path=$app
if [[ -n "${serverName[$app]}" ]]; then
app_path=${serverName[$app]}
fi
clone()
{
repo=${dRepo[$code_dir]}
echo "clone from repo: $repo ..."
rm -rf ${code_dir}
git clone --single-branch -b develop -c core.symlinks=true ${repo}
}
build()
{
cd ${code_dir}
if [[ -a "pom.xml" ]]; then
mvn clean install
fi
cd ${app_path}
mvn package spring-boot:repackage
}
logconfig()
{
cp -r ${DEVSTACK}/common-config/* ${DEVSTACK_WORKSPACE}/${code_dir}/${app_path}/src/main/resources/
}
package()
{
clone
logconfig
build
}
deploy()
{
remote=${remoteHost[$app]}
if [[ -z ${remote} ]]; then
echo "need param host ip but is blank ..."
exit 1
fi
ips=(${remote})
for ip in "${ips[@]}"; do
echo "deploy $app to host $ip ..."
ssh digital@${ip} 'mkdir /home/digital/app' || true
scp ${code_dir}/${app_path}/target/*.jar digital@${ip}:/home/digital/app/app.jar
ssh digital@${ip} 'bash -s' < ${DEVSTACK}/publish/start.sh restart app prod
done
}
if [[ $1 == "package" ]]; then
package
elif [[ $1 == "deploy" ]]; then
deploy
fi
这是一个自动打包发布的脚本,当然这不重要,重要的是我们分理出一些常规的shell脚本命令。
比如:分支判断、循环、列表、字符串判空、判断文件存在等,下面主要讲解这些用法,这里也是做一个记录防止后面自己忘记。
- 判断字符串为空
if [[ -z $A ]]; then
...
fi
- 判断字符串不为空
if [[ -n $A ]]; then
...
fi
- 判断文件存在
if [[ -d $file ]]; then
...
fi
- 数组,()可以将空格分割的字符串转为数组
A="a b c"
arr=($A)
如果字符串不是以空格分割,比如以/分割
## 以/分割项目路径,在根目录执行全局编译 mvn clean install
OLD_IFS="$IFS"
IFS="/"
arr=(${name})
IFS="$OLD_IFS"
- 循环
for i in "${!arr[@]}"; do
...
done
以上是shell常用的基本命令,还有一些很常用的技巧或者工作:
- 有时候执行批命令行,不想因为某个错误(例如文件已存在)导致shell执行中断,可以这样:
do something may be exception... || true
shell在处理复杂的跟外界交互的命令时可能会接收到格式化的字符串返回值,例如json。
shell自身不能很优雅的处理json。并且shell也没有数据类型,这也是它不能称之为语言的原因之一。但我们可以借助一些工具,让其具有处理json的能力,可以安装jq,在centos下yum install jq即可,demo:
version="$(aws ec2 describe-tags --region cn-northwest-1 --filters "Name=resource-id,Values=${instanceId}" "Name=key,Values=version" | jq '.Tags[0].Value' | sed 's/"//g')"
这个例子是调用aws cli获取ec2本身的tag,但其为json格式,我们用jq就可以方便的取出对应的value。
https://implements.tech/2019/02/26/DevOps%E4%B9%8Bshell%E5%B8%B8%E8%A7%84%E7%94%A8%E6%B3%95/