directory

  1. Basic commands
  2. variable
  3. Create and run the script
  4. conditions
  5. cycle
  6. function
  7. Others (read, mktemp, trap)

function

Let’s start with a previous example. This example demonstrates array element deletion and array destruction. In this example, the code for looping to print the array is the same, but it’s written three times, which doesn’t meet the requirements of high cohesion and low coupling. Therefore, Shell scripts provide functions to solve this problem.

array[0]=0
array[1]=1
array[2]=2

Print the full array contents
for item in ${array[@]}
do
    echo ${item}
done

Delete the element at index position 1 and print 1, 2
unset array[1]
for item in ${array[@]}
do
    echo ${item}
done

Delete the entire array and print the contents empty
unset array
for item in ${array[@]}
do
    echo ${item}
done
Copy the code

After modifying the above code to use function optimization, it can be converted to:

printArray() {
	for item in ${array[@]}
    do
        echo ${item}
    done
}

array[0]=0
array[1]=1
array[2]=2

Print the full array contents
printArray

Delete the element at index position 1 and print 1, 2
unset array[1]
printArray()

Delete the entire array and print the contents empty
unset array
printArray()
Copy the code

Delete function

unset printArray
Copy the code

Function parameters

The body of a function can use parameter variables to obtain function parameters. Function parameter variables are the same as script parameter variables.

  • The $1~$9: the first through ninth arguments to the function.
  • $0: The name of the script where the function resides.
  • $#: The total number of arguments to the function.
  • $@: All parameters of a function, separated by Spaces.
  • $*: All parameters of a function. Variables are used between parameters$IFSValues are delimited by the first character, which defaults to Spaces, but can be customized.

If the function has more than nine arguments, the tenth argument can be referred to in the form ${10}, and so on.

#! /bin/bash

printArray() {
  echo "printArray: $@"
  echo "$0: The $1 $2 $3 $4"
  echo "$@"
  echo "$# arguments"
  return -1
}

alice 1 2 3 4
echo $?
Copy the code

The scope of a variable

Not only can functions read and modify global variables directly, such as array, as seen above, but internal variables can also be read directly from outside. To set variables that can be read only from inside the function, use the local keyword

#! /bin/bash
#The test script. Sh
fn () {
  gvar=0
  local lvar
  lvar=1
  echo "fn: gvar = $gvar, lvar = $lvar"
}

fn
echo "global: gvar = $gvar, lvar = $lvar"
Copy the code