Shell script functions (function parameter transfer, recursion, library creation)

One, Shell function

  • Write the sequence of commands together in a format
  • Easy to reuse command sequence

1.Shell function definition

方法一:
function 函数名 {
    
    
命令序列
}

方法二:
函数名() {
    
    
命令序列
}

2. The return value of the function

return means to exit the function and return an exit value, which can be displayed by the $? variable in the script

Usage principles:
1. Take the return value as soon as the function ends, because the $? variable only returns the exit status code of the last command executed.
2. The exit status code must be 0~255, and the value will be divided by 256 if it exceeds

return

Insert picture description here
Insert picture description here

echo

Insert picture description here
Insert picture description here

Two, function parameter transfer

#!/bin/bash
sum() {
    
    
s=$[$1 + $2]
echo $s
}
read -p "请输入第一个参数:" first
read -p "请输入第二个参数:" second
sum $first $second

Insert picture description here
Insert picture description here

Three, the scope of function variables

  • Functions in Shell scripts are only valid in the current Shell environment
  • Variables in Shell scripts are globally effective by default
  • Use the local command to limit the variable to the function
    Insert picture description here
    Insert picture description here

Insert picture description here
Insert picture description here

Four, recursion

1. Factorial

fact() {
    
    
if [ $1 -eq 1 ]
then
  echo 1
else
  local temp=$[$1 - 1]
  local result=$(fact $temp)
echo $[$1 * $result]
fi
}
  read -p "请输入:" n
  result=$(fact $n)
  echo $result

Insert picture description here
Insert picture description here

2. Recursive directory

#!/bin/bash
listdir () {
    
    
for i in $1/*
do
  if [ -d $i ]
  then
    echo "$2$i:"
    listdir $i " $2"
  else
    echo "$2$i"
  fi
done
}
read -p "请输出目录名:" dir
listdir $dir ""

Insert picture description here
Insert picture description here

Five, create a library

Insert picture description here
Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/IHBOS/article/details/114642860