LEARN FROM:http://learn.akae.cn/media/ch31s03.html
1.變量
環境變量可以從父進程傳給子進程,因此Shell進程的環境變量可以從當前Shell進程傳給fork
出來的子進程。用printenv
命令可以顯示當前Shell進程的環境變量.用set
命令可以顯示當前Shell進程中定義的所有變量(包括本地變量和環境變量)和函數.
本地變量:$ VARNAME=value 注意等號兩邊都不能有空格,否則會被Shell解釋成命令和命令行參數。
子進程shell變量導出:$ export VARNAME=value 這樣父進程的Shell也可以使用這個變量
2.通配符
ls ch[012][0-9].doc
3.命令代換
由反引號括起來的也是一條命令,Shell先執行該命令,然后將輸出結果立刻代換到當前命令行中。例如定義一個變量存放date
命令的輸出:
DATE=$(date)
4.算數代換
用于算術計算,$(())
中的Shell變量取值將轉換成整數
5.轉義“\”
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 向左偏移 ,$#代表傳進參數的個數 而$@是具體的內容,當執行shift的時候,$#和$@也會相應的改變。
#! /bin/bash
echo "the number of params $#"
echo "the contents of params $@"
shift
echo "num:$# contents:$@"
shift
echo "num:$# contents:$@"
8.函數
#! /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.調試
Shell提供了一些用于調試腳本的選項,如下所示:
- -n
-
讀一遍腳本中的命令但不執行,用于檢查腳本中的語法錯誤
- -v
-
一邊執行腳本,一邊將執行過的腳本命令打印到標準錯誤輸出
- -x
-
提供跟蹤執行信息,將執行的每一條命令和結果依次打印出來
使用這些選項有三種方法,一是在命令行提供參數
set -x
和
set +x
分別表示啟用和禁用
-x
參數,這樣可以只對腳本中的某一段進行跟蹤調試。
從今天的一些編碼來看,Shell編程要注意腳本中的空格,在if,while語句中 “[ ]”要留空格,以及變量的定義中,等號兩端不要存有空格。