[Bash] Understand and Use Functions in Bash

n this lesson, we'll go over how bash functions work. Bash functions work like mini bash scripts--you can pass parameters and invoke them just like a bash command. You can also define local variables within a bash function using the local keyword. Local variables follow similar scope rules present in most programming languages.

 
Define and call a function:
//script.sh
greet() {
  echo "hello world"
}

greet  // call a function
 

Pass parameters to the function:

greet() {
  echo "$1 world"
}

greet  "hello"

$1: means the first param passed in to the function.

Get the return value:

greet() {
  return "$1 world"
}

greet "Hello"

greeting = $(greet "Hello")

$(): get the return as a result.

Global vs local variables:

global = 123

test() {
  echo "global = $global"
  local local_var = "i am a local"
  echo "local_var = $local_var"
}
原文地址:https://www.cnblogs.com/Answer1215/p/10129333.html