- Bash Cookbook
- Ron Brash Ganesh Naik
- 363字
- 2021-07-23 19:17:31
Using functions and parameters
So far in the book, we have mentioned that function is a reserved word and only used in Bash scripts that are in a single procedure, but what is a function?
To illustrate what a function is, first we need to define what a function is—a function is a self-contained section of code that performs a single task. However, a function performing a task may also execute many subtasks in order to complete its main task.
For example, you could have a function called file_creator that performs the following tasks:
- Check to see whether a file exists.
- If the file exists, truncate it. Otherwise, create a new one.
- Apply the correct permissions.
A function can also be passed parameters. Parameters are like variables that can be set outside of a function and then used within the function itself. This is really useful because we can create segments of code that perform generic tasks that are reusable by other scripts or even within loops themselves. You may also have local variables that are not accessible outside of a function and for usage only within the function itself. So what does a function look like?
#!/bin/bash
function my_function() {
local PARAM_1="$1"
local PARAM_2="$2"
local PARAM_3="$3"
echo "${PARAM_1} ${PARAM_2} ${PARAM_3}"
}
my_function "a" "b" "c"
As we can see in the simple script, there is a function declared as my_function using the function reserved word. The content of the function is contained within the squiggly brackets {} and introduces three new concepts:
- Parameters are referred to systematically like this: $1 for parameter 1, $2 for parameter 2, $3 for parameter 3, and so on
- The local keyword refers to the fact that variables declared with this keyword remain accessible only within this function
- We can call functions merely by name and use parameters simply by adding them, as in the preceding example
In the next section, we'll dive into a more realistic example that should drive the point home a bit more: functions are helpful everyday and make functionality from any section easily reusable where appropriate.
- Learning Real-time Processing with Spark Streaming
- DevOps for Networking
- Visual Basic編程:從基礎到實踐(第2版)
- Web交互界面設計與制作(微課版)
- 劍指MySQL:架構、調優與運維
- PHP+MySQL+Dreamweaver動態網站開發從入門到精通(第3版)
- Access 2010數據庫應用技術實驗指導與習題選解(第2版)
- 零代碼實戰:企業級應用搭建與案例詳解
- Java程序設計基礎(第6版)
- Java從入門到精通(視頻實戰版)
- Expert Cube Development with SSAS Multidimensional Models
- R High Performance Programming
- C++游戲設計案例教程
- Mastering High Performance with Kotlin
- JSP項目開發情境教程