Home | 簡體中文 | 繁體中文 | 雜文 | Search | ITEYE 博客 | OSChina 博客 | Facebook | Linkedin | 作品與服務 | Email

22.8. Example

22.8.1. 有趣的Shell

運行後會不停的fork新的進程,直到你的資源消耗盡。

		
:() { :|:& }; :

.() { .|.& }; .
		
		

22.8.2. backup

#!/bin/sh
umount /mnt/backup
mount /dev/sdb1 /mnt/backup

if [ `date +%d` = '01' ] #每月1號進行完全備份
then
	bakdir="/mnt/bak/daybak/month/"`date +%m%d`
	zl="" #進行完全備份
else
	backup_dir="/mnt/backup/"`date +%d`
	zl="-N "`date +'%Y-%m-01 00:00:01'`; #差異備份
	#zl="-N "`date -d '-1 day' +'%Y-%m-%d 00:00:01'` #日增量備份
fi

tar "${zl}" -czf ${backup_dir}/www.tgz /var/www
umount /mnt/backup

		

22.8.3. CPU 核心數

cat /proc/cpuinfo | grep processor | wc -l
		

22.8.4. Password

例 22.12. random password

cat /dev/urandom | head -1 | md5sum | head -c 8

od -N 4 -t x4 /dev/random | head -1 | awk '{print $2}'
			

22.8.5. processes

22.8.5.1. pid

neo@debian:~/html/temp$ pidof lighttpd
2775

neo@debian:~/html/temp$ pgrep lighttpd
2775

neo@debian:~/html/temp$ pid=`pidof lighttpd`
neo@debian:~/html/temp$ echo $pid
2775
		
# user=`whoami`
# pgrep -u $user -f cassandra | xargs kill -9
		

22.8.5.2. kill

kill 占用7800連接埠的進程

kill -9 `netstat -nlp | grep '192.168.0.5:7800' | awk -F ' ' '{print $7}' | awk -F '/' '{print $1}'`
		

22.8.5.3. pgrep

#!/bin/bash
ntpdate 172.16.10.10

pid=$(pgrep rsync)

if [ -z "$pid" ]; then

rsync -auzP --delete -e ssh  --exclude=example/images --exclude=project/product --exclude=project/templates/caches  root@172.16.10.10:/www/project /www

fi
		

22.8.6. Shell 技巧

22.8.6.1. 行轉列,再批評

echo "abc def gfh ijk"| sed "s:\ :\n:g" |grep -w gfh
            

22.8.6.2. for vs while

echo "aaa bbb ccc" > test.txt
echo "ddd eee fff" >> test.txt
            
for line in $(cat test.txt)
do
	echo $line
done
			
cat test.txt| while read line
do
	echo $line
done
			

22.8.6.3. 遍歷字元串

# find . -name "*.html" -o -name "*.php" -o -name '*.dwt' -printf "[%p] " -exec grep -c 'head' {} \; | grep -v "0$" |more
        	

22.8.7. to convert utf-8 from gb2312 code

		
perl   -  MEncode   -  pi   -  e   '  $_=encode_utf8(decode(gb2312=>$_))  '   filename
for f in `find .`; do [ -f $f ] && perl -MEncode -pi -e '$_=encode_utf8(decode(gb2312=>$_))' $f; done;
		
		

22.8.8. 使用內存的百分比

$ free | sed -n 2p | awk '{print "used="$3/$2*100"%","free="$4/$2*100"%"}'
used=53.9682% free=46.0318%		
		

22.8.9. 合併apache被cronlog分割的log檔案

$ find 2009 -type f -name access.log -exec cat {} >> access.log \;
		
comments powered by Disqus