Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Shell 程式設計

Shell 腳本實用小片段集

取得腳本所在目錄

FILE_DIR=`echo $(cd $(dirname $0); pwd)`

數值計算

整數運算可用 expr,非整數則交給 awk 的內建函數:

awk 'BEGIN{printf("%d", 1.7+0.5)}'   # 四捨五入
awk 'BEGIN{printf "%.2f\n", 2/3}'    # 保留小數

用 (()) 做遞增

while read line
do
    ((lineNum++))
done < inputfile

計數的效能選擇

在檔案中找關鍵字時,grep -c XXX 比 grep XXX | wc -l 快。但查行程時必須寫成 ps -ef | grep XXX | grep -v grep | wc -l,因為要把 grep 自己的行程濾掉。

顯示上下文

grep -A4 '#!/bin/bash' dir.sh    # -A4 表示連後四行一起印出

cut 的字元與欄位切割

echo abcdefghi | cut -b2-5        # bcde
echo abcdefghi | cut -c2-5        # bcde
echo abc:def:hij:kmn | cut -d: -f2-3   # def:hij

捕獲訊號

#!/bin/bash
function handle
{
    echo "received a signal"
}
trap 'handle' HUP INT QUIT TSTP
sleep 5

用 stty 與 dd 做到「按任意鍵繼續」

#!/bin/sh
function char
{
    settty=$(stty -g)
    stty raw
    stty -echo
    dd if=/dev/tty bs=1 count=1 2> /dev/null
    stty echo
    stty -raw
    stty $settty
}
echo -n "press any key to continue..."
input=`char`

先把終端切到 raw 且不回顯,讀一個字元後再還原成原本的設定,這樣就不會出現按鍵被印在畫面上或需要按 Enter 的問題。

其他

perl -e 'print time'
mkdir -p test/{inc,src,help/{html,pdf,doc}}   # 一行建立整個目錄樹
Copyright © Linux教程網 All Rights Reserved