Shell编程(七)函数

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

 

posted @ 2019-02-13 22:25  douzujun  阅读(183)  评论(0编辑  收藏  举报