|
蓝森林 http://www.lslnet.com 2006年8月18日 15:18
(原創) Linux Shell 編程 bash
Linux Shell 編程
Bash Shell具有和其它程式語言一樣的編程能力, 用戶可以用它來設計出更跟功能
強大的Shell 腳本程式, 它由 Linux 命令組成
提供有條件,循環等控制語句.
變量
Linux變量可以分為系統內部變量,系統環境變量,用戶變量 ,並且linux shell腳本中的變量是非特定
類型的.
系統內部變量是由系統提供的,用戶可以訪問但是不可以改變它的值
系統環境變量也由系統描述系統環境的變量,有一些用戶可以修改.
用戶變量是由用戶在編寫shell腳本程式時自己定義的變量, 使用前用戶必須定義.可隨意修改和訪問.
常用的系統變量
$* 運行shell 腳本所傳遞的全部參數的自符串
$# 運行shell 腳本所傳遞的全部參數的數目
$@ 運行shell 腳本所傳遞的全部參數組成的列表
$0 shell 腳本程式名稱
$n 運行shell 腳本程式中的第n個參數值
$? 執行上一個命令的返回值
$$ 運行shell 腳本程序的PID
$! 執行的上一個後台命令的PID
test 命令
test 表達式 或 [ 表達式 ]
* String expressions:: <colon>; match substr index length quote
* Numeric expressions:: + - * / %
* File type tests:: -[bcdfhLpSt]
* Access permission tests:: -[gkruwxOG]
* File characteristics tests:: -e -s -nt -ot -ef
* String tests:: -z -n = !=
* Numeric tests:: -eq -ne -lt -le -gt -ge
* Connectives for test:: ! -a -o
條件語句
1 為假, 0為真
if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMM
ANDS; ] fi
if [ -x /bin/sh ] ; then
/bin/sh ;
fi
分支語句
case: case WORD in [PATTERN [| PATTERN]...) COMMANDS ;;]... esac
read KTYPE
case "$KTYPE" in
yes|true)
echo 'the value is yes or true';
;;
not)
echo 'the value is not';
;;
*)
echo ' unkown '
esac
循環語句
1.>; for 語句用法
for: for NAME [in WORDS ... ;] do COMMANDS; done
for afile in /home/oracle/dblog/*; do
echo $afile ;
tail -n 2 $afile ;
done
2.>; while 語句用法
while: while COMMANDS; do COMMANDS; done
i=1
while [ $i -le 30 ] ;do
echo $i ;
i=`e
done
3.>; until 語句用法
until: until COMMANDS; do COMMANDS; done
i=1
until [ $i -ge 30 ] ;do
echo $i ;
i=`expr $i + 1` ;
done
自定義函數
function NAME { COMMANDS ; } or NAME () { COMMANDS ; }
mc=()
{
mkdir -p ~/.mc/tmp 2>;/dev/null;
chmod 700 ~/.mc/tmp;
MC=~/.mc/tmp/mc-$$;
/usr/bin/mc -P "$@" >;"$MC";
cd "`cat $MC`";
/bin/rm "$MC";
unset MC
}
實例:
本shell程式可以掃瞄某一網絡的所有電腦端口號是否打開,從而可以了解該網段電腦所提供了
一些什麼服務.
$. scan.sh 172.17.8 21 /*尋求所有的ftp server
$. scan.sh 172.17.8 23 /*尋求所有的telnet server
$. scan.sh 172.17.8 80 /*尋求所有的web server
scan.sh
#!/bin/sh
if test "$1" = "" ; then
echo Needs network.
exit 1
fi
if test "$2" = "" ; then
echo Needs ports.
exit 1
fi
i=1
while [ $i -le 254 ] ; do
host=$1.$i;
nc -nz -w 1 $host $2
stat=$?
if test "$stat" = "0" ; then
echo -e "\\t$host\\t$2\\t(open)"
fi
i=`expr $i + 1` ;
done
作者: 阿飛
日期:2004-01-15 |
(原創) Linux Shell 編程 bash
还可以讲了变量和基本语句,
好像还缺少函数呀,望楼主补全
顶~~~~~~~~~~~~ |
| |