-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
19-functions.sh
104 lines (84 loc) · 2.16 KB
/
19-functions.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
echo "
##################################
## Example 19.1: #
## defining & calling a function #
##################################
"
say_hello() {
echo 'hello!'
}
say_hello
# $? prints the exit code of a function or program
echo $?
echo "
##########################
## Example 19.2: #
## a function that fails #
##########################
"
failing_function() {
echo 'I fail!'
# by default, functions return 0 (success)
return 1
}
failing_function
# $? prints the exit code of a function or program
echo $?
echo "
########################################
## Example 19.3: #
## how to take arguments in a function #
########################################
"
say_hello() {
name=$1
echo "Hello, $name!"
}
say_hello "Ahmed"
echo "
#####################################
## Example 19.4: #
## a function with a local variable #
#####################################
"
set_some_variables() {
globalvar=$1
local localvar
localvar=$1
}
set_some_variables "panda"
# localvar was local to the function, so it's not available
# outside of the function
echo "localvar=$localvar"
echo "globalvar=$globalvar"
echo "
######################################################
## Example 19.4: #
## very weird thing: local x=VALUE suppresses errors #
######################################################
"
example_function1() {
local x=$(asdf)
}
example_function2() {
local x
x=$(asdf)
}
# this function succeeds, even though it has this "asdf:
# command not found" error
example_function1
echo "example_function1 exit code: $?"
# this function fails, like it should
example_function2
echo "example_function2 exit code: $?"
echo "
#####################################################
## Example 19.5: #
## functions need to be defined before they're used #
#####################################################
"
my_function # error: not found
my_function() {
echo "my_function got called"
}
my_function # now it works