您的位置:首页 > 运维架构 > Shell

shell脚本实例

2016-03-31 16:20 567 查看
代码如下:
<pre name="code" class="html">#!/bin/bash# clean job info from database which created 60 days ago# before clean data, get offset from bns, then delay [offset * 1800] s# if get offset failed. clean operation will not be executedreadonly MYSQL_HOSTNAME=xxreadonly PORT=xxreadonly USER=xxreadonly PASSWORD=xxreadonly TABLE=xx.xxreadonly TEST_BNS=xxreadonly PROXY_BNS=xxreadonly WORKSPACE=$(cd $(dirname $0); pwd)readonly LOCAL_HOSTNAME=`hostname`readonly HOSTNAME=${LOCAL_HOSTNAME/.baidu.com/}readonly DATE=-60dayreadonly CREATE_TIME="$(date -d $DATE '+%F %H:%M:%S')"readonly DEL_OPERATION="DELETE  FROM $TABLE WHERE create_time < '$CREATE_TIME' limit 1000"readonly SELECT_OPERATION="select count(*) as cnt FROM $TABLE WHERE create_time < '$CREATE_TIME'"#get bns offset, if failed, gen random number: [0-4]offset=-1multiply_factor=1800#record how many data left in databasecount=-1Prompt(){echo "[$(date '+%D %H:%M:%S')] $@"}ok() {echo "[ok] ${1}"}#gen random number between [1, 5]randNumber() {tmp=$RANDOMoffset=$[ tmp % 5 ]}delayTime() {#here we cannot check $?, which is aways 0tmp=$(get_instance_by_service "$PROXY_BNS" -o | grep "$HOSTNAME" | awk '{print $2}')if [ "$tmp"x = ""x ]; thenPrompt "get bns offset failed, clean operation will not be executed.."exit -1elseoffset=$tmpPrompt "get bns offset success, bns offset: $offset"fi}delOperation() {mysql  -h $MYSQL_HOSTNAME -P$PORT -u$USER -p$PASSWORD -e "${DEL_OPERATION}"}countOperation() {declare countTmp=`mysql  -h $MYSQL_HOSTNAME -P$PORT -u$USER -p$PASSWORD -e "${SELECT_OPERATION}"`if [ "$countTmp"x = ""x ]; thenPrompt "count expired job failed, left clean operation will not be executed.."exit -1elsecount=$(echo $countTmp | awk '{print $2}')Prompt "count expired job success, [$count] job-data left"fi}#only reserve data whose create_time within 60 dayscleanExpiredData() {Prompt "select operation is $SELECT_OPERATION "Prompt "delete operation is $SELECT_OPERATION "Prompt "will del jobs where create_time < $CREATE_TIME"countOperationwhile [ $count -gt 0 ]dodelOperationcountOperationdone}start() {delayTimeif [ $offset -eq -1 ]; thenPrompt "get factor for delay time failed, please check.."exit -1elseok "get factor for delay time success"fisleeptime=$[ offset * multiply_factor ]Prompt "clean mysql data after $sleeptime seconds .."sleep $sleeptimePrompt "wake up from sleep, start to clean data .."cleanExpiredDataif [ $? -eq 0 ]; thenok "clean data success."elsePrompt "clean data failed .."exit -1fi}start

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: