一,shell 傳參指的是 linux 命令參數傳參給shell 程序
$0 相當於argv[0] 獲取linux 命令 不帶參數 $1、$2... 位置參數(Positional Parameter),python函數的argv[1]、argv[2]... $# 獲取所有的參數 個數 $@ 表示參數列表"$1" "$2" ...,例如可以用在for循環中的in后面。 $* 表示參數列表"$1" "$2" ...,同上 $? 上一條命令的Exit Status $$ 當前進程號
shift 命令表示參數集體左移
#! /bin/sh echo "The program $0 is now running" echo "The first parameter is $1" echo "The second parameter is $2" echo "The parameter list is $@" shift # 表示后面所有的參數都會左移一個 echo "The first parameter is $1" echo "The second parameter is $2" echo "The parameter list is $@"
二,shell 函數:
1,Shell中也有函數的概念,但是函數定義中沒有返回值也沒有參數列表
2,shell函數內同樣是用$0、$1、$2等變量來提取參數
3,Shell腳本中的函數必須先定義后調用,也就是定義必須在調用的前面 這也是由於是解釋語言的原因
4,return后面跟一個數字則表示函數的Exit Status
#! /bin/sh #如果 傳參是文件名 不是文件夾名稱 那么返回 #沒有形參列表 () is_directory() { DIR_NAME=$1 if [ ! -d $DIR_NAME ]; then return 1 else return 0 fi } for DIR in "$@"; do #給函數傳參 if is_directory "$DIR" then : else echo "$DIR doesn't exist. Creating it now..." #如果創建文件失敗 錯誤信息打印到 /dev/null # 2 文件描述符 錯誤信息stderr, 1 文件描述符 輸出信息stdout, 0文件描述符 鍵盤輸入 stdin # 2>&1 也就是將錯誤信息輸出到 /dev/null 別再給我打印出來了 mkdir $DIR > /dev/null 2>&1 if [ $? -ne 0 ]; then # -ne 不等於 echo "Cannot create directory $DIR" exit 1 fi fi done