shell note

行for循环

for i in `seq -w 0 23`; do for j in `seq -w 0 5 59`; do echo 20120917$i$j; done done

 

日期时间左补零

leftpad=`echo $1 | sed 's/^/0/g' | sed -r 's/.+(..)$/\1/g'`

 

凑时间,凑整点

TIME=`date '+%s' -d '10 minutes ago'`
echo 'NOW: '`date -d "@$TIME" +'%Y%m%d%H%M'`

TIME=$(($TIME - $PERIOD * 60 - 10#`date -d "@$TIME" +'%M'` % $PERIOD * 60))
TIME=`date -d "@$TIME" +'%Y%m%d%H%M'`
DATE=${TIME:0:8}
HH=${TIME:8:2}
MM=${TIME:10:2}

echo "TIME: $TIME, DATE: $DATE, HH: $HH, MM: $MM"
exit

 

筛选文件,sum size

total=0; for i in $(for h in `seq -w 9 23`; do for m in 00 10 15 25 30 40 45 55; do ls -s 2012_10_22-${h}-${m}.log; done done | sed -r 's/^([^ ]+) .+/\1/g'); do total=`expr $total + $i`; done; echo `expr $total / 1024 / 1024`G

 

fifo

mkfifo q99999
for i in `seq -w 0 999`; do echo "hello.${i}" > q99999; done &
tail -f q99999

 

囧 重大发现 shell原来有数组,另外可以把输出用管道发送给while,不用再生成临时文件了

ls -l . | sed -r -e '/^total /d' | while read line; do
    #echo $line
    line=(`echo $line | sed -r -e 's/\s+/" "/g' -e 's/^/"/' -e 's/\n$/"/'`)
    for i in `seq 0 ${#line[@]}`; do 
        echo $i. ${line[i]}; 
    done
done

 

满是图片的文件夹,瞬间变网页

 

if [ ! -d img ]; then
    mkdir img
fi
prev=''; curr=''; ls | grep -v img | while read f; do
    if [ "$prev" = '' ]; then
        prev=$f
    elif [ "$curr" = '' ]; then
        echo "<a href=\"${f}.html\"><img src=\"img/$prev\" /></a>" > img/${prev}.html
        curr=$f
    else
        echo "<a href=\"${f}.html\"><img src=\"img/$curr\" /></a><a href=\"${prev}.html\">$prev</a>" > img/${curr}.html
        prev=$curr
        curr=$f
    fi
    #echo "$prev < $curr > $f"
done
curr=`ls | grep -v img | tail -n 1`; prev=`ls | grep -v img | tail -n 2 | head -n 1`; echo "<img src=\"img/$curr\" /><a href=\"${prev}.html\">$prev</a>" > img/${curr}.html
mv img/`ls | grep -v img | head -n 1`.html img/index.html
mv `ls | grep -v img | tr '\n' ' '` img/
mv img/*.html .

  

logger.sh

test ! $logs && logs=$(cd `dirname $0`; pwd)/logs
test -d "$logs" || mkdir "$logs"
log(){
    LOG_FILE=$logs/`basename $0 | sed -r 's/\.[^\.]+$//'`.`date '+%Y%m%d'`
    touch $LOG_FILE
    echo "`date '+%Y-%m-%d %H:%M:%S'` - $$ $1" >> $LOG_FILE
    return 0
}

log 'logger ready!'

 

 

监控维持单个进程

#!/bin/sh

BASE=$(cd `dirname $0`; pwd)
cd $BASE

. $BASE/logger.sh
log 'hi :-]'
 
if [ $# -lt 1 ] || [ ! -f $1 ]; then
    log 'at least one argument, a exist file is required!'
fi
cmd="$*"

pids="$logs/`basename $1 | sed -r 's/\.[^\.]+$//'`.pid"
if [ ! -f "$pids" ]; then
    echo $$ > "$pids"
fi
pid=`head -n 1 "$pids"`
if [ "$pid" -eq "$$" ]; then
    log "[$cmd] starting"
elif [ "$pid" -ne "$$" -a `ps -ef | grep -P "^[^\s]+\s+$pid\s" | grep -v 'grep' | wc -l` -gt 0 ]; then
    log "[$cmd] on running"
    exit
else
    log "[$cmd] new starting"
    echo $$ > "$pids"
fi

(eval "$cmd") &
wait
log "[$cmd] stoped"

 

 

你可能感兴趣的:(shell)