Linux及shell脚本学习笔记----6 函数

1 函数

1.1 定义

function  NAME(){
    command1
    command2
    ...
}
省略关键字function
NAME(){
     command1
     ...
}

例子:

#!/bin/bash
function sayHello(){
    echo "Hello"
}
sayHello        #函数调用

1.2 函数的返回值

函数的返回值又叫函数的退出状态。
例子:

#!/bin/bash
FILE=/etc/notExistFile

function checkFileExist(){
      if [ -f $FILE ]; then
              return 0
      else
              return 1
      fi
}

echo "Call function checkFileExist" #提示函数调用
checkFileExist
RTV=$?     #将函数返回值保存在变量中
if [ $RTV -eq 0]; then
      echo "$FILE exist"
else
      echo "FILE not exist"
fi

2 带参数的函数

2.1 位置参数

#!/bin/bash
function checkFileExist(){
      if [ -f $1]; then
              return 0
      else
              return 1
      fi
}

echo "Call function checkFileExist" #提示函数调用
checkFileExist
RTV=$?     #将函数返回值保存在变量中
if [ $RTV -eq 0]; then
      echo "$1 exist"
else
      echo "$1 not exist" 
fi

2.2 指定位置参数

set命令给指定脚本指定位置参数(又叫重置)
例子:一个 set01.sh 脚本

#!/bin/bash
set 1 2 3 4 5 6
for i in $@
do
       echo "Here \$$COUNT is $i"
       let "COUNT++"
done

运行 bash set01.sh a b c d e f

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值