[Bash] Understand and Use Functions in Bash

admin2024-08-22  8

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 " world"
}

greet  "hello"

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

 

Get the return value:

greet() {
  return " 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"
}

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明原文出处。如若内容造成侵权/违法违规/事实不符,请联系SD编程学习网:675289112@qq.com进行投诉反馈,一经查实,立即删除!