Shell basics-day7-function(2)

1. The use of positional parameters

#!/bin/bash
  
# $# 代表参数的个数
# 提示用户使用该命令的正确格式
if [ $# -ne 3 ];then 
        echo "usage: `basename $0` par1 par2 par3"
        exit
fi        
         
fun3(){
    
     
        echo "$(($1 * $2 * $3))"
}            
      
result=`fun3 $1 $2 $3`
echo "result is: $result"

2. The use of array parameters in shell functions

#!/bin/bash
num=(1 2 3 4 5)
#echo "${num[@]}"

array(){
    
    
        #不加关键字local的情况下,变量在函数外也是可以使用的
        factorial=1
        #注意这里的  $@  和  $*  一样表示所有参数,在函数外使用的含义结合
        #位置参数的作用理解
        for i in "$@"
        do
                factorial=$[factorial * $i]
        done
        echo "$factorial"
}

array ${num[@]}    #${num[@]}数组所有元素的值

3. The method of shell function returning array.
You can use echo statement to print out the contents of the array and assign it to another array. In this way, the value of the array can be output.

#!/usr/bin/bash
num=(1 2 3 4 5)

array(){
    
    
        local newarray=(`echo $*`)
        local i
        #$#表示的数组的长度
        for((i=0;i <=$#;i++))
        do
              newarray[$i]=$(( ${newarray[$i]} * 5 ))
        done
        echo "${newarray[*]}"
}

result=`array ${
     
     num[@]}`    #${num[@]}数组所有元素的值,需要注意的是``中的命令是在子shell中执行的,如果在函数中定义#全局变量,``中执行完函数的时候,在当前的shell中是没有变量的,这个细节需要注意
echo ${result[*]}

You can also use positional parameters, the code is as follows:

#!/bin/bash
num=(1 2 3 4 5)

array(){
    
    
        for i in $*
        do
              newarray[j++]=$[$i*5]
        done
        echo "${newarray[*]}"
}

result=`array ${
     
     num[@]}`    #${num[@]}数组所有元素的值
echo ${result[*]}

4. The shell's built-in commands
break and continue have the same meaning as the C language
exit. When this command is executed, the program exits.
The meaning of the shift command: shift the positional parameter to the left

Guess you like

Origin blog.csdn.net/xiaoan08133192/article/details/112276571