shell技巧

 
 

如何實現Shell腳本以DEAMON的方式運行,即實現Shell版的Fork

 
 
if [ "$1" != 'background' ] ; then scriptdir=$(cd "$(dirname "$0")"; pwd) scriptname=`basename $0` nohup /bin/bash ${scriptdir}/${scriptname} background &>/dev/null & exit 0 fi echo "do some thing"
 
 

如何獲取當前shell腳本所在的文件夾路徑

 
 
SHELLDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
 
 

如何正確判斷變量,避免語法錯誤

 
 
[ "x$var" == "x" ]
 
 

如何kill一個進程樹,即kill掉父進程和全部子進程(在沒有找到命令以前,我在網上找到的shell版)

 
 
#使用方法,treekill pid treekill(){ local father=$1 childs=(`ps -ef | awk -v father=$father 'BEGIN{ ORS=" "; } $3==father{ print $2; }'`) if [ ${#childs[@]} -ne 0 ] ; then for child in ${childs[*]} do treekill $child done fi kill -9 $father }
 
 

如何快速檢測base腳本的語法錯誤,又不用執行腳本

 
 
#如下命令 並不會真正執行腳本,只會檢查xx.sh的語法 bash -n xx.sh
 
 

如何在bash中產生必定範圍的隨機數

 
 
## 使用方法 ## ##get_random 10 30 function get_random() { local start_num=$1 local end_num=$2 local range1=`expr $end_num - $start_num` local range2=`expr $RANDOM % $range1` local ran_num=`expr $start_num + $range2` echo $ran_num }



0
. shell 調試 複製代碼 代碼以下: sh -x somefile.sh 在somefile.sh 文件里加上set+x set-x 1. 用 && || 簡化if else 複製代碼 代碼以下: gzip -t a.tar.gz if [[ 0 == $? ]]; then echo "good zip" else echo "bad zip" fi 能夠簡化爲: 複製代碼 代碼以下: gzip -t a.tar.gz && echo "good zip" || echo "bad zip" 2. 判斷文件非空 複製代碼 代碼以下: if [[ -s $file ]]; then echo "not empty" fi 3. 獲取文件大小 複製代碼 代碼以下: stat -c %s $file stat --printf='%s\n' $file wc -c $file 4. 字符串替換 複製代碼 代碼以下: ${string//pattern/replacement} a='a,b,c' echo ${a//,/ /} 5. Contains 子字符串? string="My string" if [[ $string == *My* ]]; then echo "It's there!" fi 6. rsync備份 複製代碼 代碼以下: rsync -r -t -v /source_folder /destination_folder rsync -r -t -v /source_folder [user@host:/destination_folder 7. 批量重命名文件 爲全部txt文件加上.bak 後綴: 複製代碼 代碼以下: rename '.txt' '.txt.bak' *.txt 去掉全部的bak後綴: 複製代碼 代碼以下: rename '*.bak' '' *.bak 把全部的空格改爲下劃線: 複製代碼 代碼以下: find path -type f -exec rename 's/ /_/g' {} \; 把文件名都改爲大寫: 複製代碼 代碼以下: find path -type f -exec rename 'y/a-z/A-Z/' {} \; 8. for/while 循環 複製代碼 代碼以下: for ((i=0; i < 10; i++)); do echo $i; done for line in $(cat a.txt); do echo $line; done for f in *.txt; do echo $f; done while read line ; do echo $line; done < a.txt cat a.txt | while read line; do echo $line; done 9. 刪除空行 複製代碼 代碼以下: cat a.txt | sed -e '/^$/d' (echo "abc"; echo ""; echo "ddd";) | awk '{if (0 != NF) print $0;}' 10. 比較文件的修改時間 複製代碼 代碼以下: [[ file1.txt -nt file2.txt ]] && echo true || echo false [[ file1.txt -ot file2.txt ]] && echo true || echo false 11. 實現Dictionary結構 複製代碼 代碼以下: hput() { eval "hkey_$1"="$2" } hget() { eval echo '${'"hkey_$1"'}' } $ hput k1 aaa $ hget k1 aaa 12. 去掉第二列 複製代碼 代碼以下: $echo 'a b c d e f' | cut -d ' ' -f1,3- $a c d e f 13. 把stderr輸出保存到變量 複製代碼 代碼以下: $ a=$( (echo 'out'; echo 'error' 1>&2) 2>&1 1>/dev/null) $ echo $a error 14. 刪除前3行 複製代碼 代碼以下: $cat a.txt | sed 1,3d 15. 讀取多個域到變量 複製代碼 代碼以下: read a b c <<< "xxx yyy zzz" 16. 遍歷數組 複製代碼 代碼以下: array=( one two three ) for i in ${array[@]} do echo $i done 17. 查看目錄大小 複製代碼 代碼以下: $ dush ~/apps 18. 查看CPU信息 複製代碼 代碼以下: $ cat /proc/cpuinfo 19. date 複製代碼 代碼以下: $ date +%Y-%m-%d 2012-12-24 $ date +%Y-%m-%d –date ‘-1 day' 2012-12-23 $ date +%Y-m-%d –date ‘Dec 25' 2011-12-25 $ date +%Y-m-%d –date ‘Dec 2510 days' 2011-12-15 20. 獲取路徑名和文件名 複製代碼 代碼以下: $ dirname ‘/home/lalor/a.txt' /home/lalor $ basename ‘/home/lalor/a.txt' a.txt 21. 並集和交集 comm 能夠用來求並集,交集,差集,假設如今有兩個文件a和b,它們的內容以下: 複製代碼 代碼以下: $cat a 1 3 5 $cat b 3 4 5 6 7 $comm a b 1 3 4 5 6 7 $comm -1 -2 a b #交集 3 5 $comm a b | sed 's/\t//g' #並集 1 2 3 4 5 6 7 $comm -1 -3 a b | sed 's/\t//g' #b-a 4 6 7 22. awk複雜分隔符 多字符做分隔符 複製代碼 代碼以下: $ echo "a||b||c||d" | awk -F '[|][|]' '{print $3}' c 多種分隔符1 複製代碼 代碼以下: $echo "a||b,#c d" | awk -F '[| ,#]+' '{print $4}' d 多種分隔符2 複製代碼 代碼以下: $echo "a||b##c|#d" | awk -F '([|][|])|([#][#])' '{print $NF}' c|#d 23. 產生一個隨機數 複製代碼 代碼以下: echo $RANDOM 24. 按照模式split 文件 複製代碼 代碼以下: csplit server.log /PATTERN/ -n 2 -s {*} -f server_result -b "%02d.log" -z /PATTERN/ 用來匹配某一行,分割過程由此開始 {*} 根據匹配,重複執行分割 -s 靜默模式 -n 分割後文件名後綴中,數字的個數 -f 分割後的文件名前綴 -b 指定後綴格式 25. 獲取文件名或者擴展名 複製代碼 代碼以下: var=hack.fun.book.txt echo ${var%.*} hack.fun.book echo ${var%%.*} hack echo ${var#.*} fun.book.txt echo ${var##.*} txt 26. 以 root 賬戶執行上一條命令。 複製代碼 代碼以下: $sudo !! 其中: * !! 是指上一條命令 * !$ 上一條命令的最後一個參數 * !* 上一條命令的全部參數 * !:3 上一條命令的第3個參數 例如: 複製代碼 代碼以下: $ls /tmp/somedir ls: cannot access /tmp/somedir: No such file or directory $mkdir !$ madir /tmp/somedir 27. 利用 python 搭建一個簡單的 Web 服務器,可經過 http://$HOSTNAME:8000 訪問。 複製代碼 代碼以下: python -m SimpleHTTPServer 28. 在 Vim 中無需權限保存編輯的文件。 複製代碼 代碼以下: :w !sudo tee % 29. 將上一條命令中的 foo 替換爲 bar,並執行。 複製代碼 代碼以下: ^foo^bar 30. 快速備份或複製文件。 複製代碼 代碼以下: cp filename{,.bak} 31. 將 ssh keys 複製到 user@host 以啓用無密碼 SSH 登陸。 複製代碼 代碼以下: $ssh-copy-id user@host 32. 把 linux 桌面錄製爲視頻。 複製代碼 代碼以下: ffmpeg -f x11grab -s wxga -r 25 -i :0.0 -sameq /tmp/out.mpg 33. man 妙用 複製代碼 代碼以下: man ascii man test 34. 在 vim 中編輯上一條命令 複製代碼 代碼以下: fc 35. 刪除0 字節文件或垃圾文件 複製代碼 代碼以下: find . -type f -size 0 -delete find . -type f -exec rm -rf {} \; find . -type f -name "a.out" -exec rm -rf {} \; find . type f -name "a.out" -delete find . type f -name "*.txt" -print0 | xargs -0 rm -f 36. 在編寫SHELL 時顯示多行信息 複製代碼 代碼以下: cat << EOF +--------------------------------------------------------------+ | === Welcome to Tunoff services === | +--------------------------------------------------------------+ EOF 注意,在指定結束符時,它必須是該行的惟一內容,而且該行必須以這個字符開頭。 37. 如何給mysql建軟連接 複製代碼 代碼以下: cd /usr/local/mysql/bin for i in * do ln /usr/local/mysql/bin/$i /usr/bin/$i done 38. 獲取IP地址: 複製代碼 代碼以下: ifconfig eth0 |grep "inet addr:" |awk '{print $2}'|cut -c 6- 39. 打開文件數目 複製代碼 代碼以下: lsof 40. 清除殭屍進程 複製代碼 代碼以下: ps -eal | awk '{ if ($2 == "Z"){ print $4}}' | kill -9 41. 打印惟一行 複製代碼 代碼以下: awk '!a[$0]++' file 42. 打印奇數行 複製代碼 代碼以下: awk 'i=!i' file awk 'NR%2' file 43. 打印匹配行後的某一行 複製代碼 代碼以下: seq 10 | awk '/4/{f=4};--f==0{print;exit}' 44. 打印某行後後面的10行 複製代碼 代碼以下: cat file | grep -A100 string cat file | grep -B100 string #前面 cat file | grep -C100 string #先後 sed -n '/string/,+100p' awk '/string/{f=100}--f>=0' 45. 獲取命令行最後一個參數 複製代碼 代碼以下: echo ${!#} echo ${$#} #錯誤的嘗試 46. 輸出重定向 若是你願你,能夠將STDERR 和 STDOUT 的輸出重定向到一個輸出文件,爲此,bash 提供了特殊的重定向符號 &> 複製代碼 代碼以下: ls file nofile &> /dev/null 咱們如何在腳本里面重定向呢?沒有什麼特別之處,和普通重定向同樣。 複製代碼 代碼以下: #!/bin/bash #redirecting output to different locations echo "now redirecting all output to another location" &>/dev/null 問題就來了,若是咱們要將全部的輸出都重定向到某個文件呢?咱們都不但願每次輸出的時候都重定向一下吧,正所謂,山人自有妙計。咱們能夠用exec 來永久重定向,以下所示: 複製代碼 代碼以下: #!/bin/bash #redirecting output to different locations exec 2>testerror echo "This is the start of the script" echo "now redirecting all output to another location" exec 1>testout echo "This output should go to testout file" echo "but this should go the the testerror file" >& 2 輸出結果以下所示: 複製代碼 代碼以下: This is the start of the script now redirecting all output to another location lalor@lalor:~/temp$ cat testout This output should go to testout file lalor@lalor:~/temp$ cat testerror but this should go the the testerror file lalor@lalor:~/temp$ 以追加的方式重定向: 複製代碼 代碼以下: exec 3 >> testout 取消重定向: 複製代碼 代碼以下: exec 3> - 47. 函數 任何地方定義的變量都是全局變量,若是要定義局部變量,需加local 關鍵字 shell中的函數也能夠用遞歸 複製代碼 代碼以下: #!/bin/bash function factorial { if [[ $1 -eq 1 ]]; then echo 1 else local temp=$[ $1 - 1 ] local result=`factorial $temp` echo $[ $result * $1 ] fi } result=`factorial 5` echo $result 建立函數庫 將函數定一個在另外一個文件,而後經過source 命令加載到當前文件 在命令行使用函數 將函數定義在~/.bashrc 中便可 向函數傳遞數組 複製代碼 代碼以下: #!/bin/bash #adding values in an array function addarray { local sum=0 local newarray newarray=(`echo "$@"`) for value in ${newarray[*]} do sum=$[ $sum+$value ] done echo $sum } myarray=(1 2 3 4 5) echo "The original array is: ${myarray[*]}" arg1=`echo ${myarray[*]}` result=`addarray $arg1` echo "The result is $result" 48.正則表達式 匹配中文字符的正則表達式:[u4e00-u9fa5] 評註:匹配中文還真是個頭疼的事,有了這個表達式就好辦了 匹配雙字節字符(包括漢字在內):[^x00-xff] 評註:能夠用來計算字符串的長度(一個雙字節字符長度計2,ASCII字符計1) 匹配空白行的正則表達式:^ *$ 評註:能夠用來刪除空白行 匹配HTML標記的正則表達式:<(S*?)[^>]*>.*?</1>|<.*? /> 評註:網上流傳的版本太糟糕,上面這個也僅僅能匹配部分,對於複雜的嵌套標記依舊無能爲力 匹配首尾空白字符的正則表達式:^s*|s*$ 評註:能夠用來刪除行首行尾的空白字符(包括空格、製表符、換頁符等等),很是有用的表達式 匹配Email地址的正則表達式:w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)* 評註:表單驗證時很實用 匹配網址URL的正則表達式:[a-zA-z]+://[^s]* 評註:網上流傳的版本功能頗有限,上面這個基本能夠知足需求 匹配賬號是否合法(字母開頭,容許5-16字節,容許字母數字下劃線):^[a-zA-Z][a-zA-Z0-9_]{4,15}$ 評註:表單驗證時很實用 匹配國內電話號碼:d{3}-d{8}|d{4}-d{7} 評註:匹配形式如0511-4405222或021-87888822 匹配騰訊QQ號:[1-9][0-9]{4,} 評註:騰訊QQ號從10000開始 匹配中國郵政編碼:[1-9]d{5}(?!d) 評註:中國郵政編碼爲6位數字 匹配身份證:d{15}|d{18} 評註:中國的身份證爲15位或18位 匹配ip地址:d+.d+.d+.d+ 評註:提取ip地址時有用 匹配特定數字: ^[1-9]d*$  //匹配正整數 ^-[1-9]d*$ //匹配負整數 ^-?[1-9]d*$  //匹配整數 ^[1-9]d*|0$ //匹配非負整數(正整數+ 0) ^-[1-9]d*|0$  //匹配非正整數(負整數+ 0) ^[1-9]d*.d*|0.d*[1-9]d*$  //匹配正浮點數 ^-([1-9]d*.d*|0.d*[1-9]d*)$ //匹配負浮點數 ^-?([1-9]d*.d*|0.d*[1-9]d*|0?.0+|0)$ //匹配浮點數 ^[1-9]d*.d*|0.d*[1-9]d*|0?.0+|0$  //匹配非負浮點數(正浮點數+ 0) ^(-([1-9]d*.d*|0.d*[1-9]d*))|0?.0+|0$  //匹配非正浮點數(負浮點數+ 0) 評註:處理大量數據時有用,具體應用時注意修正 匹配特定字符串: ^[A-Za-z]+$  //匹配由26個英文字母組成的字符串 ^[A-Z]+$  //匹配由26個英文字母的大寫組成的字符串 ^[a-z]+$  //匹配由26個英文字母的小寫組成的字符串 ^[A-Za-z0-9]+$  //匹配由數字和26個英文字母組成的字符串 ^w+$  //匹配由數字、26個英文字母或者下劃線組成的字符串 猜你還感興趣:      
1qaz#RFV 
相關文章
相關標籤/搜索