shell脚本基础(function函数)

函数是一串命令的集合,函数可以把大的命令集合分解成若干较小的任务。编程人员可以基于函数进一步的构造更复杂的Shell 程序,而不需要重复编写相同的代码。下面给出了Linux Shell中函数的基本形式

            function_name()
           {
                command1
                command2
                …
                commandN
            }

示例一

vim function1.sh 
#function1.sh
#!/bin/bash

hello()
{
    echo "Hello, today is `date`"
}

echo "Now going to run function hello()"
hello

echo "end the function hello()"

示例二

 vim function2.sh
#function2.sh
#!/bin/bash

output()
{
     for(( num1 = 1; num1 <= 5; num1++ ))
     do
         echo -n "$num1 "
     done 
}

let "num2=1"
while [ "$num2" -le 5 ]
do
    output
    echo ""
    let "num2=num2 + 1"
done

示例三

vim function3.sh 
#function3.sh
#!/bin/bash

directory()
{
    let "filenum = 0"
    let "dirnum = 0"
    
    ls
    echo ""
    
    for file in $( ls )
    do
        if [  -d $file ]
        then
            let "dirnum = dirnum + 1"
        else
           let "filenum = filenum + 1"
        fi
    done

    echo "The number of directory is $dirnum"
    echo "The number of file is $filenum"
}

directory 
  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值