Functions#
A function is a repeatable unit of code. We've defined two in our script:
1 2 3 4 5 6 7 8 9 10 |
|
Defining a function is simple. You need a name, a pair of ()
s, which aren't used for defining parameters like in other languages; and a pair of {}
s, which define the function's body.
1 2 3 |
|
The name is how you call the function later on, which we'll look at. It's like a variable in that regard: a variable name is how you reference the data, and a function is how you reference/call the code inside of it.
Functions are very powerful and enable you to repeat a unit of logic (code) over and over.
The function's body is where our code is written. Everything inside of the function's {}
s is the body. Like this:
1 2 3 |
|
The body, or the code in it, can be virtually anything. You can call other functions, you can send messages to remote networks, you can read files, and way more.
Our hello
function uses the Bash function echo
to print a message to the console/terminal.
Arguments#
In a lot of languages, a function can take arguments. Bash is no different, but it just takes them in a different manner. In Python, for example, you put what arguments you want the function to receive inside of the ()
s when creating the function. In Bash, however, you use $0
, $1
, to reference the arguments.
Let's look at an example:
1 2 3 4 5 6 |
|
This gives us this result:
1 2 3 |
|
But why did we get script_example_2.sh
and not hello
? The $0
argument is a special variable that usually contains the name of the script we've executed. We can see I called the script script_example_2.sh
. If we change our script we can get the correct output we expected:
1 2 3 4 5 6 |
|
Then we get:
1 2 3 |
|
Which is what we originally expected.
Now you have a basic understanding of functions and arguments to functions.
Calling Functions#
In our original script we call our functions in a "special" sort of way:
1 |
|
We use the $()
syntax inside of a string ("
). Just before that, though, we call the functions directly by simply using the names of them: hello
and world
.
The cool thing about the $()
syntax is you can call other programs too. Anything that can be found inside your $PATH
variable can be called inside of $()
. Example time!
1 |
|
I get this:
1 2 |
|
Obviously you'll get a different date if you're in another time-zone.
Going back to our original script, you should be able to break it down easily enough. If not, have a play with it - break it and try things. That's the cool thing about code, you can break it and it affects absolutely no one (expect you.)