LEARN FROM:http://learn.akae.cn/media/ch31s03.html
1.變量
環(huán)境變量可以從父進程傳給子進程,因此Shell進程的環(huán)境變量可以從當(dāng)前Shell進程傳給fork
出來的子進程。用printenv
命令可以顯示當(dāng)前Shell進程的環(huán)境變量.用set
命令可以顯示當(dāng)前Shell進程中定義的所有變量(包括本地變量和環(huán)境變量)和函數(shù).
本地變量:$ VARNAME=value 注意等號兩邊都不能有空格,否則會被Shell解釋成命令和命令行參數(shù)。
子進程shell變量導(dǎo)出:$ export VARNAME=value 這樣父進程的Shell也可以使用這個變量
2.通配符
ls ch[012][0-9].doc
3.命令代換
由反引號括起來的也是一條命令,Shell先執(zhí)行該命令,然后將輸出結(jié)果立刻代換到當(dāng)前命令行中。例如定義一個變量存放date
命令的輸出:
DATE=$(date)
4.算數(shù)代換
用于算術(shù)計算,$(())
中的Shell變量取值將轉(zhuǎn)換成整數(shù)
5.轉(zhuǎn)義“\”
6.條件測試
7.控制
case
#! /bin/sh
echo "is it moring? Please answer yes or no ."
read YES_OR_NO
case "$YES_OR_NO" in
yes|Yes|y|YES)
echo "Good Moring!";;
[nN]*)
echo "Good afternoon.";;
*)
echo "Sorry, $YES_OR_NO not recognized. Enter yes or no . "
exit 1;;
esac
exit 0
for
#! /bin/sh
for FRUIT in apple banana pear ; do
echo "I like $FRUIT"
done
if
#! /bash/sh
echo "is it morning? please answer yes or no ."
read YES_OR_NO
if [ "$YES_OR_NO" = "yes" ]; then
echo "Good Morning."
elif [ "$YES_OR_NO" = "no" ]; then
echo "Good afternoon."
else
echo "Sorry ,$YES_OR_NO not recognized.Enter yes or no."
exit 1
fi
exit 0
While
#! /bin/sh
echo "Enter Password:"
read TRY
while [ "$TRY" != "p" ]; do
echo "Sorry, Try again"
read TRY
done
Shift
#! /bin/bash
echo "the number of params $#"
echo "the contents of params $@"
shift
echo "$1"
shift
echo "$1"
shift
echo "$1"
shift 向左偏移 ,$#代表傳進參數(shù)的個數(shù) 而$@是具體的內(nèi)容,當(dāng)執(zhí)行shift的時候,$#和$@也會相應(yīng)的改變。
#! /bin/bash
echo "the number of params $#"
echo "the contents of params $@"
shift
echo "num:$# contents:$@"
shift
echo "num:$# contents:$@"
8.函數(shù)
#! /bin/sh
is_d()
{
DIR_NAME=$1
if ( test -d $DIR_NAME ); then
return 1
else
return 0
fi
}
for DIR in "$@" ; do
if is_d "$DIR"
then :
else
echo "not a dir"
fi
done
9.調(diào)試
Shell提供了一些用于調(diào)試腳本的選項,如下所示:
- -n
-
讀一遍腳本中的命令但不執(zhí)行,用于檢查腳本中的語法錯誤
- -v
-
一邊執(zhí)行腳本,一邊將執(zhí)行過的腳本命令打印到標準錯誤輸出
- -x
-
提供跟蹤執(zhí)行信息,將執(zhí)行的每一條命令和結(jié)果依次打印出來
使用這些選項有三種方法,一是在命令行提供參數(shù)
set -x
和
set +x
分別表示啟用和禁用
-x
參數(shù),這樣可以只對腳本中的某一段進行跟蹤調(diào)試。
從今天的一些編碼來看,Shell編程要注意腳本中的空格,在if,while語句中 “[ ]”要留空格,以及變量的定義中,等號兩端不要存有空格。