1. 程式人生 > >Shell編程(七)函數

Shell編程(七)函數

cal ima ret tro start 編程 don 指向 art

1. 函數開始

#!/bin/bash

foo() 
{
    echo "Function foo is called";
}

echo "-=start=-"

foo

echo "-=end=-"

技術分享圖片

2. 帶參數

#!/bin/bash

fun()
{
    echo "hello"
    echo $0
    echo $1
    echo $2
    echo "Hello"
}

echo "--start--"
fun aa bb 11
echo "--end--"

技術分享圖片

#!/bin/bash

is_director()
{
    DIR_NAME
=$1 if [ ! -d $DIR_NAME ]; then return 1 else return 0 fi } for DIR in "$@"; do if is_director "$DIR" then : else echo "$DIR doesn‘t exist. Creating is now..." mkdir $DIR > /dev/null 2>&1 # 運行失敗打印,標準輸出到/dev/null,標準出錯指向1,1指向/dev/null if
[ $? -ne 0 ]; then # if !0 -> wrong echo "Cannot create directory $DIR" exit 1 fi fi done

技術分享圖片

註意:

mkdir /aaa > /dev/null 2>&1

技術分享圖片

技術分享圖片

Shell編程(七)函數