天天看點

筆記1:shell中的八進制和crond執行指令那些事

最近工作中寫腳本遇到兩個問題

1、crond不能執行ifconfig指令

2、0開頭的變量按8進制計算

一、背景,最近工作中要每小時統計日志數量,封裝成指定的json,然後通過post發送給伺服器,于是寫了下面的腳本

<code>#!/bin/bash</code>

<code>count_file=/tos/etc/ips_kafka/kafka_count.json</code>

<code>cp $count_file $count_file".bak"</code>

<code>send=$count_file".bak"</code>

<code>ip=`cat /SE/ts_ip`</code>

<code>url=/api/xty/eqpt-log-report/recevie</code>

<code>#eqpt_ip</code>

<code>eqip=`ifconfig eth2 |grep "inet addr:"|awk -F ':' '{print $2}'|awk '{print $1}'`</code>

<code>sed -i 's/"eqpt_ip":/"eqpt_ip":'"\"$eqip\""',/g' $send</code>

<code>#date</code>

<code>date=`date +%Y-%m-%d`</code>

<code>#hour</code>

<code>hour=`date +%H`</code>

<code>((hour--))</code>

<code>start="$date $hour:00:00"</code>

<code>end="$date $hour:59:59"</code>

<code>sed -i 's/"time_id":/"time_id":'"\"$hour\""',/g' $send</code>

<code>#count</code>

<code>count=`mysql -uuser -ppasswod -e "use ngtos;select count(*) from table where time between '$start' and '$end';" -s |tail -n 1`</code>

<code>#tatal</code>

<code>sed -i 's/"total":/"total":'$count',/g' $send</code>

<code>sed -i 's/"warn_toal":/"warn_toal":'$count',/g' $send</code>

<code>bc=`cat /SE/branch_code`</code>

<code>sed -i 's/"branch_code":/"branch_code":'"\"$bc\""',/g' $send</code>

<code>#send_time</code>

<code>send_time=`date +"%Y-%m-%d %H:%M:%S"`</code>

<code>echo $send_time</code>

<code>sed -i 's/"send_time":/"send_time":'"\"$send_time\""'/g' $send</code>

<code>msg=`cat $send`</code>

<code>watch_log=`du -sk /SE/kfktime.log |awk '{print $1}'`</code>

<code>if [ $watch_log -ge "10240" ];then</code>

<code>sed -i '1,1000d' /SE/kfktime.log</code>

<code>fi</code>

<code>echo "$msg" &gt;&gt;/SE/kfktime.log</code>

<code>watch_log=`du -sk /SE/kfk_send_count.log |awk '{print $1}'`</code>

<code>sed -i '1,1000d' /SE/kfk_send_count.log</code>

​<code>​curl -H "Content-Type:application/json" http://$ip$url -d "$msg" &gt;&gt; /SE/kfk_send_count.log 2&gt;&amp;1 &amp;​</code>​

二、發現問題和解決問題

然後運作了一天,通過log日志發下了1和2兩個問題

首先,所有的發送資訊都沒有eth2的ip位址也就是問題1

然後,發現當小時是08 09的時候,執行--就存在問題

問題1:原因分析,手動執行沒有任何問題,crond去執行就擷取不到eth2。接下來我将eqip進行重定向,發現為空,然後就想到crond的環境變量應該沒有ifconfig的路徑。

然後which看了下ifconfig的路徑為/sbin/ifconfig。

解決方法:在腳本中添加了ifconfig的路徑後檔案解決。

問題2:原因分析,發現問題08 09執行--還是08 09,然後我就單獨寫了腳本執行((08--)),然後提示“((: 08: value too great for base (error token is "08")",

因為在shell中0開頭認為是8進制,08 09壓根就不會存在,是以出現這個問題。

解決方法:在08前加10#表示是10進制,問題解決。

修改後:

<code>eqip=`/sbin/ifconfig eth2 |grep "inet addr:"|awk -F ':' '{print $2}'|awk '{print $1}'`</code>

<code>hour=10#`date +%H`</code>

<code>if [ "$hour" == "10#00" ];then</code>

<code>hour=23</code>

<code>elif [ "$hour" == "10#01" ];then</code>

<code>hour=24</code>

<code>else</code>