shell实现自动化部署项目
shell获取命令的返回值
res=`docker run -dti -v $rootdir:/monitor -v /etc/localtime:/etc/localtime:ro 86912afeeaa8 /bin/bash`
echo $res
echo "${res} container is running....."
字符串和变量拼接
imagedir="$rootdir/docker/escron.tar"
shell单双引号的区别
windows和linux平台兼容
用vi/vim命令打开脚本文件,输入“:set fileformat=unix”,回车,保存退出
写入单行文本和多行文本
单行文本
echo Hello > filename.txt
多行文本
cat>${shelldir}/hostcron.sh<<EOF
#! /bin/bash
docker exec ${res} /bin/bash /monitor/shell/crontbday.sh
echo $(date "+%Y-%m-%d %H:%M:%S") >>${rootdir}/msgday.log
echo \$(date "+%Y-%m-%d %H:%M:%S") >>${rootdir}/msgday.log \表示转义字符 后面的命令做为字符串写入到文件 而不是把命令的执行结果写入到文件
EOF
sed命令中使用变量
把命令中的单引号变成双引号
#sed -i 's/ip=.*/ip=10.10.10.10/' ${filedir}
sed -i "s/ip=.*/ip=$ip/" ${filedir}
实例代码
#! /bin/bash #执行此脚本需要root用户权限 read -p "Enter your es server Ip, please: " ip echo $ip basedir=`cd $(dirname $0); pwd -P;` rootdir=$(dirname $basedir) echo "the root dir is $rootdir" echo "setting the es server ip" filedir="$rootdir/common/esConfig.py" #sed -i 's/ip=.*/ip=${ip}/' ${filedir} sed -i "s/ip=.*/ip=\"$ip\"/" ${filedir} echo 'loadding docker images' imagedir="$rootdir/docker/escron.tar" echo "the image at ${imagedir}" docker load -i $imagedir echo "loadding docker image complete...." echo 'run a docker container......' res=`docker run -dti -v $rootdir:/monitor -v /etc/localtime:/etc/localtime:ro 86912afeeaa8 /bin/bash` echo $res echo "${res} container is running....." shelldir="$rootdir/shell" echo "update the containerID to the shell" cat>${shelldir}/hostcron.sh<<EOF #! /bin/bash docker exec ${res} /bin/bash /monitor/shell/crontb.sh echo \$(date "+%Y-%m-%d %H:%M:%S") >>${rootdir}/msg.log EOF cat>${shelldir}/hostcronday.sh<<EOF #! /bin/bash docker exec ${res} /bin/bash /monitor/shell/crontbday.sh echo \$(date "+%Y-%m-%d %H:%M:%S") >>${rootdir}/msgday.log EOF echo 'setting the system crontab' echo "*/60 * * * * sh ${shelldir}/hostcron.sh" >> /var/spool/cron/root echo "1 0 * * * sh ${shelldir}/hostcronday.sh" >> /var/spool/cron/root echo "the task is success finished.....!"
本文来自博客园,作者:不懂123,转载请注明原文链接:https://www.cnblogs.com/yxh168/p/12133824.html