Skip to content

Commit ba47e4b

Browse files
[Term Entry]Command line Bash: Functions (#6941)
* [Edit] SQL: DATEDIFF() * Update datediff.md * [Term Entry]Command line Bash: Functions * Update content/command-line/concepts/bash/terms/functions/functions.md * Update content/command-line/concepts/bash/terms/functions/functions.md * Update content/command-line/concepts/bash/terms/functions/functions.md ---------
1 parent 4084ef4 commit ba47e4b

File tree

1 file changed

+278
-0
lines changed
  • content/command-line/concepts/bash/terms/functions

1 file changed

+278
-0
lines changed
Lines changed: 278 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,278 @@
1+
---
2+
Title: 'Functions'
3+
Description: 'Creates reusable blocks of code that group commands under a single name for modular scripting.'
4+
Subjects:
5+
- 'Bash/Shell'
6+
- 'Computer Science'
7+
Tags:
8+
- 'Bash/Shell'
9+
- 'Command Line'
10+
- 'Functions'
11+
CatalogContent:
12+
- 'learn-the-command-line'
13+
- 'paths/computer-science'
14+
---
15+
16+
A **function** in Bash is a reusable block of code that groups a set of commands under a single name. Functions enable you to organize code into logical units, reduce repetition, and make scripts more maintainable and readable. When called, a function executes all the commands within its body and can optionally return a value to the calling code.
17+
18+
Functions are essential building blocks in Bash scripting for automating repetitive tasks, creating modular code architecture, and implementing complex workflows. They are commonly used in system administration scripts, deployment automation, data processing pipelines, and interactive command-line tools where the same operations must be performed multiple times with different inputs.
19+
20+
## Syntax
21+
22+
```pseudo
23+
function_name() {
24+
# Commands to execute
25+
command1
26+
command2
27+
# ...
28+
}
29+
30+
# Calling the function
31+
function_name
32+
```
33+
34+
**Alternative syntax:**
35+
36+
```pseudo
37+
function function_name {
38+
# Commands to execute
39+
command1
40+
command2
41+
# ...
42+
}
43+
44+
# Calling the function
45+
function_name
46+
```
47+
48+
**Parameters:**
49+
50+
- `function_name`: The name identifier for the function. Should be descriptive and follow naming conventions
51+
- `{ }`: Curly braces that define the function body containing the commands to execute
52+
- `command1`, `command2`: The actual Bash commands that will be executed when the function is called
53+
54+
**Arguments and Return Values:**
55+
56+
- Functions can accept arguments accessed through `$1`, `$2`, `$3`, etc., representing the first, second, third arguments respectively
57+
- `$#` contains the number of arguments passed to the function
58+
- `$@` and `$*` represent all arguments passed to the function
59+
- Functions return the exit status of the last executed command, or an explicit value using `return`
60+
61+
## Example 1: Basic Function Creation
62+
63+
This example demonstrates how to create and call a simple function that displays a greeting message:
64+
65+
```bash
66+
#!/bin/bash
67+
68+
# Define a simple greeting function
69+
greet_user() {
70+
echo "Welcome to Bash scripting!"
71+
echo "Today's date is: $(date +%Y-%m-%d)"
72+
echo "Have a productive day!"
73+
}
74+
75+
# Call the function
76+
echo "Starting the program..."
77+
greet_user
78+
echo "Program completed."
79+
```
80+
81+
The output of the above code will be:
82+
83+
```shell
84+
Starting the program...
85+
Welcome to Bash scripting!
86+
Today's date is: 2025-05-30
87+
Have a productive day!
88+
Program completed.
89+
```
90+
91+
This example shows the basic structure of a Bash function. The `greet_user()` function is defined with three echo commands that display welcome messages and the current date. The function is then called by simply using its name. The function definition must appear before any calls to the function in the script.
92+
93+
## Example 2: Function with Parameters
94+
95+
This example demonstrates how to create a function that accepts parameters and uses them to perform calculations:
96+
97+
```bash
98+
#!/bin/bash
99+
100+
# Function to calculate the area of a rectangle
101+
calculate_area() {
102+
local length=$1 # First argument
103+
local width=$2 # Second argument
104+
105+
# Validate input parameters
106+
if [ $# -ne 2 ]; then
107+
echo "Error: Function requires exactly 2 arguments (length and width)"
108+
return 1
109+
fi
110+
111+
# Calculate area
112+
local area=$((length * width))
113+
114+
# Display results
115+
echo "Rectangle dimensions: ${length} x ${width}"
116+
echo "Calculated area: ${area} square units"
117+
118+
# Return the area for potential use by calling code
119+
return 0
120+
}
121+
122+
# Test the function with different parameters
123+
echo "=== Area Calculator ==="
124+
calculate_area 5 3
125+
echo ""
126+
calculate_area 12 8
127+
echo ""
128+
calculate_area 7 # This will trigger an error
129+
```
130+
131+
The output generated by this code will be:
132+
133+
```shell
134+
=== Area Calculator ===
135+
Rectangle dimensions: 5 x 3
136+
Calculated area: 15 square units
137+
138+
Rectangle dimensions: 12 x 8
139+
Calculated area: 96 square units
140+
141+
Error: Function requires exactly 2 arguments (length and width)
142+
```
143+
144+
This example illustrates how functions can accept and process parameters. The `calculate_area()` function takes two arguments (length and width), validates the input, performs arithmetic operations, and provides feedback. The `local` keyword ensures variables are scoped to the function, preventing conflicts with global variables.
145+
146+
## Example 3: System Information Utility
147+
148+
This example shows a practical function for gathering and displaying system information, demonstrating real-world usage:
149+
150+
```bash
151+
#!/bin/bash
152+
153+
# Function to display comprehensive system information
154+
show_system_info() {
155+
local info_type=${1:-"all"} # Default to "all" if no parameter provided
156+
157+
echo "=== System Information Report ==="
158+
echo "Generated on: $(date)"
159+
echo ""
160+
161+
case $info_type in
162+
"basic"|"all")
163+
echo "--- Basic System Info ---"
164+
echo "Hostname: $(hostname)"
165+
echo "Operating System: $(uname -s)"
166+
echo "Kernel Version: $(uname -r)"
167+
echo "Architecture: $(uname -m)"
168+
echo ""
169+
;& # Fall through to next case
170+
"resources"|"all")
171+
echo "--- System Resources ---"
172+
echo "CPU Information:"
173+
echo " Processor: $(grep 'model name' /proc/cpuinfo | head -1 | cut -d':' -f2 | xargs)"
174+
echo " CPU Cores: $(nproc)"
175+
echo ""
176+
echo "Memory Information:"
177+
echo " Total RAM: $(free -h | grep 'Mem:' | awk '{print $2}')"
178+
echo " Available RAM: $(free -h | grep 'Mem:' | awk '{print $7}')"
179+
echo ""
180+
echo "Disk Usage:"
181+
df -h / | tail -1 | awk '{print " Root partition: " $3 " used of " $2 " (" $5 " full)"}'
182+
echo ""
183+
;&
184+
"network"|"all")
185+
if [ "$info_type" = "network" ] || [ "$info_type" = "all" ]; then
186+
echo "--- Network Information ---"
187+
echo "IP Address: $(hostname -I | awk '{print $1}')"
188+
echo "Network Interfaces:"
189+
ip -o link show | awk '{print " " $2}' | sed 's/://'
190+
echo ""
191+
fi
192+
;;
193+
*)
194+
echo "Error: Invalid info type. Use 'basic', 'resources', 'network', or 'all'"
195+
return 1
196+
;;
197+
esac
198+
199+
echo "Report generation completed."
200+
return 0
201+
}
202+
203+
# Demonstrate function usage with different parameters
204+
echo "Generating full system report:"
205+
show_system_info
206+
echo -e "\n" | head -2
207+
208+
echo "Generating basic info only:"
209+
show_system_info "basic"
210+
```
211+
212+
The output of this code will be:
213+
214+
```shell
215+
Generating full system report:
216+
=== System Information Report ===
217+
Generated on: Fri May 30 12:00:00 UTC 2025
218+
219+
--- Basic System Info ---
220+
Hostname: myserver
221+
Operating System: Linux
222+
Kernel Version: 5.4.0-74-generic
223+
Architecture: x86_64
224+
225+
--- System Resources ---
226+
CPU Information:
227+
Processor: Intel(R) Core(TM) i7-8700K CPU @ 3.70GHz
228+
CPU Cores: 8
229+
230+
Memory Information:
231+
Total RAM: 16Gi
232+
Available RAM: 12Gi
233+
234+
Disk Usage:
235+
Root partition: 45G used of 100G (45% full)
236+
237+
--- Network Information ---
238+
IP Address: 192.168.1.100
239+
Network Interfaces:
240+
lo
241+
eth0
242+
wlan0
243+
244+
Report generation completed.
245+
246+
247+
Generating basic info only:
248+
=== System Information Report ===
249+
Generated on: Fri May 30 12:00:00 UTC 2025
250+
251+
--- Basic System Info ---
252+
Hostname: myserver
253+
Operating System: Linux
254+
Kernel Version: 5.4.0-74-generic
255+
Architecture: x86_64
256+
257+
Report generation completed.
258+
```
259+
260+
This advanced example demonstrates a utility function that gathers system information. It showcases parameter handling with default values, conditional logic using case statements, command substitution for gathering system data, and practical system administration tasks. The function can be called with different parameters to display specific types of information.
261+
262+
## Frequently Asked Questions
263+
264+
### 1. Can I use variables declared inside a function outside of it?
265+
266+
By default, variables in Bash functions are global unless explicitly declared with the `local` keyword. However, it's best practice to use `local` for variables that should only exist within the function to avoid naming conflicts and unexpected behavior.
267+
268+
### 2. How do I return values from a Bash function?
269+
270+
Bash functions can return exit status codes (0-255) using the `return` command. For returning actual data, you can use `echo` to output the result and capture it with command substitution: `result=$(my_function)`.
271+
272+
### 3. What happens if I don't provide the required arguments to a function?
273+
274+
The function will still execute, but the missing arguments will be empty. You should implement input validation within your functions to check for required parameters using conditional statements and the `$#` variable.
275+
276+
### 4. Can I call a function before defining it in the script?
277+
278+
No, function definitions must appear before any calls to the function in the script. Bash reads and processes the script sequentially, so the function must be known before invoking it.

0 commit comments

Comments
 (0)