Understanding Functions
local graph
Chapter 10 — Understanding Functions
Section titled “Chapter 10 — Understanding Functions”Functions are an important component of pretty much every modern programming language. They’re simply blocks of code that each perform one specific task. The cool thing about them is that they allow programmers to reuse code. That is, one block of code can be called either from within a program in various places, or it can be called by various different programs from function libraries. In this chapter, I’ll show you the basics about using functions in shell scripts.
Topics in this chapter include:
- Introduction to functions
- Defining a function
- Using functions in shell scripts
- Creating function libraries
- Looking at some real-world examples
If you’re ready, let’s get started.
Technical Requirements
Use any of your Linux virtual machines or your Linux host machine.
Also, as always, you can grab the scripts and text files from Github, like so:
git clone https://github.com/PacktPublishing/The-Ultimate-Linux-Shell-Scripting-Guide.gitIntroduction to Functions
As I’ve mentioned above, a function is a block of programming code that performs a specific task. What makes functions so cool is that they really cut down on the amount of code that you have to type. Instead of having to type in the same code every time you want to perform a task, you can just call the function, instead. This cuts down on the size of your scripts, and makes typing the script much less prone to error.
Also, after a function has been called the first time, it resides in system memory, which can enhance the performance of your scripts.
You can create functions that accept parameters from the main program, that return values to the main program, or that might do some stand-alone task that doesn’t involve either passing parameters or passing values. Learning to create functions is easy, because for the most part you’re just using the same coding techniques that I’ve already shown you. I mean, yeah, there are some new things that you’ll have to learn, but there’s really nothing hard about any of it.
If you’re running Linux on your workstation, you’re already using a lot of functions without realizing it. To see the functions that your system is running, just run a declare -F command, like so:
[donnie@fedora ~]$ declare -Fdeclare -f __expand_tilde_by_refdeclare -f __fzf_comprundeclare -f __fzf_defc......declare -f gawkpath_prependdeclare -f quotedeclare -f quote_readline[donnie@fedora ~]$These functions are loaded into system memory by the shell every time you log into your computer, and are used by the various utilities that make up the bash ecosystem.
Running declare with a lower case -f also shows you the code for each function. You can also list the name of a function to only see the code for it, like this:
[donnie@fedora ~]$ declare -f __expand_tilde_by_ref__expand_tilde_by_ref (){ if [[ $1- == \~* ]]; then eval $1="$(printf ~q "$1#~")"; fi}[donnie@fedora ~]$To see where these functions are defined, you’ll need to enter debugger mode and then use a declare -F command, like this:
[donnie@fedora ~]$ bash --debugger[donnie@fedora ~]$ declare -F __expand_tilde_by_ref__expand_tilde_by_ref 1069 /usr/share/bash-completion/bash_completion[donnie@fedora ~]$So, you see that this function is defined on line number 1069 of the bash_completion function library file that’s in the /usr/share/bash-completion/ directory. Go ahead and peek into that file, and you’ll see that many functions are defined in it. When you’re through with debugger mode, just type exit.
You can also obtain information about a function with the type command, like so:
[donnie@fedora ~]$ type quotequote is a functionquote (){ local quoted=${1//\'/\\\'}; printf "%s" "$quoted"}[donnie@fedora ~]$Now that you know what functions are, let’s see if we can define some.
Defining a Function
Section titled “Defining a Function”You can define a function in the following places:
- On the command-line
- In a shell script
- In a function library
- In a shell configuration file
Defining a function from the command-line can be useful if you need to do any quick testing or experimentation with new code. Here’s what it looks like:
[donnie@fedora ~]$ howdy() { echo "Howdy, world!" ; echo "How's it going?"; }[donnie@fedora ~]$ howdyHowdy, world!How's it going?[donnie@fedora ~]$The name of this function is howdy, and the () tells the shell that this is a function. The code for the function is within the pair of curly braces. The function consists of two echo commands, which are separated by a semi-colon. Note that you need to place another semi-colon at the end of the final command. You also need to have one blank space between the first curly brace and the first command, and the final semi-colon and the closing curly brace.
Some tutorials that you’ll find might tell you that you can begin the function with the keyword function, as you see here:
[donnie@fedora ~]$ function howdy() { echo "Howdy, world!" ; echo "How's it going?"; }[donnie@fedora ~]$ howdyBut, creating functions without the function keyword works well, so there’s no real reason to use it.
Be aware that using the function keyword is a really bad idea, because it’s not portable. I mean, it works on bash, zsh, and ash, but it doesn’t work on ksh, dash, or Bourne Shell. Even where you can use the function keyword, it serves no real purpose. So, your best bet is to just never use it.
Any functions that you define on the command line will be ephemeral and will disappear as soon as you close the terminal. So, you’ll want to commit them to a file to make them permanent. Also, any functions that you define on the command-line will not be visible in a bash —debug session, because they don’t get exported to a child shell.
There’s no difference in how you would create a function in shell scripts, function library files, and shell configuration files. But, there a couple of different methods for how you structure your functions.
The first method is to place the entire function on a single line, with or without the preceding function keyword. This would look exactly as it would if you were to create a function on the command-line. Since you’ve already seen that, I’ll say no more about it.
The other method is to structure your functions in a multi-line format, as you would do in other programming languages such as C or Java. This is really your best bet, because it makes your code much more readable and less prone to error. A quick way to see how that looks is to view the single-line howdy function that I just created on the command-line with declare -f, like so:
[donnie@fedora ~]$ declare -f howdyhowdy (){ echo "Howdy, world!"; echo "How's it going?"}[donnie@fedora ~]$The declare -f command automatically converts the function that I entered on the command-line into multi-line format. If I wanted to, I could just copy and paste this into a shell script file. In fact, I think I will copy it into a new howdy_func.sh script. Here’s what it will look like:
#!/bin/bashhowdy (){ echo "Howdy, world!"; echo "How's it going?"}As before, the preceding function keyword is optional. I’ve chosen to omit it, since it serves no function and isn’t compatible with some non-bash shells.
Okay, this all looks good, but watch what happens when I run the script:
[donnie@fedora ~]$ ./howdy_func.sh[donnie@fedora ~]$Nothing happens, which isn’t good. I’ll show you why in the next section.
Using Functions in Shell Scripts
You’ll be amazed at how functions can make your shell scripts so much more functional. (Yeah, I know. That really was a bad pun.) Read on to see how to make that happen.
Creating and Calling Functions
When you place a function inside a shell script, the function code won’t get executed until you call the function. Let’s modify the howdy_func.sh script to make that happen, like this:
#!/bin/bashhowdy (){ echo "Howdy, world!"; echo "How's it going?"}howdyYou see that all I had to do was to place the name of the function outside of the function code block. Also, note that the function definition must come before the function call. Otherwise, the shell will never be able to find the function. Anyway, when I run the script now, it works fine:
[donnie@fedora ~]$ ./howdy_func.shHowdy, world!How's it going?[donnie@fedora ~]$I should also point out that the first curly brace can be on a line by itself as you see above, or it can be on the same line as the function name, like this:
#!/bin/bashhowdy() { echo "Howdy, world!" echo "How's it going?"}howdyI personally prefer this way for a simple reason. It’s just that my preferred text editor is vim, and placing the first curly brace on the same line as the function name causes vim to activate its automatic indenting feature.
The ability to reuse code is one of the coolest features about functions. Instead of having to type the same code in every place where you need to perform a certain task, just type it once and call it from wherever you need to. Let’s make another slight modification to the howdy_func .sh script, like so:
#!/bin/bashhowdy (){ echo "Howdy, world!"; echo "How's it going?"}howdyechoecho "Let's do some more stuff and then"echo "we'll call the function again."echohowdyHere’s what running the modified script looks like:
[donnie@fedora ~]$ ./howdy_func.shHowdy, world!How's it going?Let's do some more stuff and thenwe'll call the function again.Howdy, world!How's it going?[donnie@fedora ~]$So, I called the function twice, and it got executed twice. How cool is that? But, it gets even better.
Passing Positional Parameters to Functions
You can also pass positional parameters into a function, the same as you can pass them into a shell script. To do that, call the function with a value that you want to pass as a positional parameter, as you see here in this greet_func .sh script:
#!/bin/bashgreetings() { echo "Greetings, $1"}greetings DonnieYou see the $1 positional parameter in the function. When I call the function, I’m passing the value Donnie into the function. Here’s what happens when I run the script:
[donnie@fedora ~]$ ./greet_func.shGreetings, Donnie[donnie@fedora ~]$You can also pass the positional parameter into the script as you normally would, and then pass it into the function, as you see here:
#!/bin/bashgreetings() { echo "Greetings, $1"}greetings $1Here’s what happens when I run this script:
[donnie@fedora ~]$ ./greet_func2.sh FrankGreetings, Frank[donnie@fedora ~]$That’s good, but it only works with one parameter. Any additional names that you pass in as parameters won’t show up in the output. You can fix that by defining additional parameters, like this:
#!/bin/bashgreetings() { echo "Greetings, $1 $2"}greetings $1 $2And, that’s fine if you know that you’ll always want to pass in a specified number of parameters. If you don’t want to limit yourself like this, use the $@ as the positional parameter. That way, you can pass in however many parameters you want each time that you run the script. Here’s what it looks like:
#!/bin/bashgreetings() { echo "Greetings, $@"}greetings $@Let’s see what it looks like when I pass in four names:
[donnie@fedora ~]$ ./greet_func4.sh Vicky Cleopatra Frank CharlieGreetings, Vicky Cleopatra Frank Charlie[donnie@fedora ~]$That looks good. But, I can still fancy it up a bit, like this:
[donnie@fedora ~]$ ./greet_func4.sh Vicky, Cleopatra, Frank, "and Charlie"!Greetings, Vicky, Cleopatra, Frank, and Charlie![donnie@fedora ~]$Pretty slick, eh? What’s even more slick is having a function pass values back to the main program.
Passing Values from a Function
Okay, here’s where I need to pause for a moment and clarify something for the veterans of other programming languages. Unlike what you may be used to with other languages, a shell scripting function cannot directly return a value to its caller, which is normally the main body of the program.
Okay, there is a return command that you can use in a function, but it’s not the same as the return command in other languages. In shell scripts, the only thing that you can pass with return is just the exit status of a command.
You can create a function that will return a value, but you have to do it with either a global variable or a combination of a local variable and command substitution. Another difference is that in other languages, variables are local by default, and you have to specify which variables are to be global. In shell scripting, it’s just the opposite. Shell scripting variables are global by default, and you have to specify which variables are to be local.
Now, for those of you who aren’t veterans of other programming languages, allow me to explain the difference between local and global variables.
A global variable can be accessed from anywhere in a script, even if you defined it within a function. For example, look at the valuepass function in this value1.sh script:
#!/bin/bashvaluepass() { textstring='Donnie is the great BeginLinux Guru'}valuepassecho $textstringHere’s what happens when I run the script:
donnie@debian12:~$ ./value1.shDonnie is the great BeginLinux Gurudonnie@debian12:~$In this script, you see that the function does nothing except to define the global textstring variable and set its value. The value of textstring is available outside of the function, which means that after calling the function, I can then echo back the value of textstring.
Now, let’s define textstring as a local variable in the value2.sh script, like so:
#!/bin/bashvaluepass() { local textstring='Donnie is the great BeginLinux Guru'}valuepassecho $textstringWatch what happens when I run the script this time:
donnie@debian12:~$ ./value2.shdonnie@debian12:~$There’s no output this time, because the local variable isn’t accessible outside of the function. Or, more accurately, the local variable isn’t directly accessible outside of the function. There are ways to make the function pass the value of a local variable to an external caller, which I’ll show you in just a few moments.
First though, I want answer a question that I know you’re anxious to ask. That is, if we can use a global variable to pass a value outside of a function, why do we need local variables? Well, it’s just that if you use nothing but global variables in your functions, you could turn your script into a debugging nightmare. That’s because if you accidentally create a variable outside of the function with the same name as a global variable that’s inside of the function, you would overwrite the value of the variable from within the function.
By using only local variables inside of functions, you avoid that problem. If you have an external variable that has the same name as a local variable that’s in a function, the external variable won’t overwrite the internal variable’s value. To demo this, let’s create the value3.sh script, like so:
#!/bin/bashvaluepass() { textstring='Donnie is the great BeginLinux Guru'}valuepassecho $textstringtextstring='Who is the great BeginLinux Guru?'echo $textstringYou see that I’ve set the textstring variable in the function back to a global variable, and I’ve defined the variable again outside of the function. Here’s what happens when I run the script now:
donnie@debian12:~$ ./value3.shDonnie is the great BeginLinux GuruWho is the great BeginLinux Guru?donnie@debian12:~$The second echo $textstring command used the new value of textstring, which overwrote the previous value. That’s fine if that’s what you want to happen, but it usually isn’t what you want to happen.
One way to have a function pass a value with a local variable is to call the function from within a command substitution construct. To demo that, create the value4.sh script, like so:
#!/bin/bashvaluepass() { local textstring='Donnie is the great BeginLinux Guru' echo "$textstring"}result=$(valuepass)echo $resultYou see here that I’ve created the external result variable, and assigned to it the value that was obtained by the $(valuepass) command substitution.
Another method for obtaining a value from a function is to use a result variable. This involves passing the name of a variable into the function when you call it, and then assigning a value to that variable inside the function. Let’s look at the value5.sh script to see how that works:
#!/bin/bashvaluepass() { local __internalvar=$1 local myresult='Shell scripting is cool!' eval $__internalvar="'$myresult'"}valuepass resultecho $resultThe valuepass result command calls the function and passes the name of the result variable into the function, via the $1 positional parameter. Understand though, that result still doesn’t have an assigned value, so the only thing that you’re passing into the function is just the name of the variable, and nothing else.
Up to this point, you’ve only seen positional parameters used to pass values into the script when you invoke the script. Here, you seen how positional parameters can also be used to pass values from the main body of a script into a function.
Inside the function, this variable name is represented by the 1 positional parameter. This variable name is assigned as the value of the local __internalvar variable. The next line assigns Shell scripting is cool! as the value of the local myresult variable. In the final line, the eval command sets the value of myresult as the value of the $__internalvar variable.
Remember that the value of the __internalvar variable is result, which is the name of the variable that we passed into the function. Also, be aware that this is now a global variable, because I didn’t specify the local keyword here. This means that its value can be passed back to the main body of the script.
So now, $__internalvar is really the result variable with Shell scripting is cool! as its assigned value.
Understand though, that you don’t want the variable name that you pass into a function to be the same as the name of the local variable that’s inside the function. Otherwise, the eval command won’t be able to properly set the value of the variable. That’s why I prefaced the name of the local variable with a pair of underscores, so that I can be sure to prevent having a variable with the same name outside of the function. (Of course, only one underscore would have sufficed, but the accepted convention is to use two underscores.)
Next, let’s create some libraries.
Creating Function Libraries
Section titled “Creating Function Libraries”For a convenient way to make your functions reusable, just place them into a function library. Then, from within your scripts, call the desired libraries with either a source command or a dot command. If you’re the only one who will ever use the libraries, you can place them in your own home directory.
If you want to make them available for everyone, you can place them in a central location, such as in the /usr/local/lib/ directory.
For a simple demonstration, I’ve created the donnie_library file in the /usr/local/lib/ directory with two simple functions. It looks like this:
howdy_world() { echo "Howdy, world!" echo "How's it going?"}howdy_georgia() { echo "Howdy, Georgia!" echo "How's it going?"}(I live in the state of Georgia, which explains the second function.)
There’s no need to set the executable permission on this file, because it only contains code that will be called in by an executable script.
Next, I created the library_demo1.sh script, which looks like this:
#!/bin/bash<!-- page: 307 (printed 300) -->source /usr/local/lib/donnie_libraryhowdy_worldYou see that I used the source command to reference the donnie_library file. I then called the howdy_world function as I would normally do. Running the script looks like this:
[donnie@fedora ~]$ ./library_demo1.shHowdy, world!How's it going?[donnie@fedora ~]$I also created the library_demo2.sh file, which looks like this:
#!/bin/bash. /usr/local/lib/donnie_libraryhowdy_georgiaThis time I replaced the source command with a dot, to show you that they both do the exact same thing.
Be aware that using the source keyword works on ash, ksh, zsh, and bash, but it doesn’t work on certain other shells, such as dash or Bourne. If you need your scripts to run on as many shells as possible, you’ll need to use the dot, and avoid using source.
I then called the second function in the library file. Running this script looks like this:
[donnie@fedora ~]$ ./library_demo2.shHowdy, Georgia!How's it going?[donnie@fedora ~]$For something a bit more practical, let’s add a network checking function, using a case..esac construct. Unfortunately, the donnie_library file is now too large to show you here in the book, but you can download it from the Github repository. Still though, I do want to point out one thing about this case..esac construct, which you see here:
network() {site="$1"case "$site" in"")site="google.com";;*)site="$1";;esac
<!-- page: 308 (printed 301) -->}Note how for the first condition I used a "") construct. The pair of double-quotes, with no blank space between them, means that no value has been passed in for the positional parameter. This also means that google.com will be used as the default site name.
Now, the library_demo3.sh script that uses this new function looks like this:
#!/bin/bash. /usr/local/lib/donnie_librarynetwork $1Running the script without supplying an argument looks like this:
[donnie@fedora ~]$ ./library_demo3.sh2023-10-27 ... Success! google.com is reachable.[donnie@fedora ~]$Here’s how it looks when I supply a valid site name as the argument:
[donnie@fedora ~]$ ./library_demo3.sh www.civicsandpolitics.com2023-10-27 ... Success! www.civicsandpolitics.com is reachable.[donnie@fedora ~]$And finally, here’s what I get when I supply an invalid site name:
[donnie@fedora ~]$ ./library_demo3.sh www.donnie.comping: www.donnie.com: Name or service not known2023-10-27 ... Network Failure for site www.donnie.com![donnie@fedora ~]$I know, it’s a crying shame that there’s no website that’s named after me. (I might have to correct that problem some day.)
And, guess what? That’s really all I have to say about function libraries. Let’s move on to the real world.
Looking at Some Real-World Examples
Section titled “Looking at Some Real-World Examples”Here are a few cool examples of functions in action. Enjoy!
Checking Network Connectivity
Section titled “Checking Network Connectivity”This function is essentially the same as the one that I’ve just shown you in the previous section. The only real difference is that I’m using an if..then construct instead of the case..esac construct.
Also, I placed this function into the actual executable script. But, you can easily move it into a library file if you desire. (I can’t show you the entire script here due to book formatting constraints, but you can download it from the Github repository. It’s the network_func.sh file.) Anyway, here’s the important part that I really want you to see:
#!/bin/bashnetwork() { if [[ $# -eq 0 ]]; then site="google.com" else site="$1" fi ... ...}networknetwork www.civicsandpolitics.comnetwork donnie.comYou see that after I defined the network() function, I called it three different times. I first called it without a positional parameter, so that it would ping google.com. I then called it with another real website and then with a fake website as the positional parameter. Here’s what I get when I run this new script:
[donnie@fedora ~]$ ./network_func.sh2023-10-27 ... Success for google.com!2023-10-27 ... Success for www.civicsandpolitics.com!ping: donnie.com: Name or service not known2023-10-27 ... Network Failure for donnie.com![donnie@fedora ~]$That part works. Let’s now look in the system log file to see if the logger utility that’s in the function actually made the appropriate log entries:
[donnie@fedora ~]$ sudo tail /var/log/messages......Oct 27 16:14:21 fedora donnie[38134]: google.com is reachable.Oct 27 16:14:23 fedora donnie[38137]: www.civicsandpolitics.com is reachable.Oct 27 16:14:23 fedora donnie[38140]: Could not reach donnie.com.[donnie@fedora ~]$Yeah, that part works too. So once again, we have achieved coolness. (Of course, you can also modify the script so that you can supply your own positional parameter as an argument. I’ll leave it to you to do that.)
Be aware that I tested this script on a Fedora machine, which still uses the old-style rsyslog log files. If you try this on Debian, you’ll need to install rsyslog yourself. By default, Debian 12 now only uses the journald logging system, and doesn’t come with rsyslog installed.
Next, is a little something that I whipped up for myself.
Using the CoinGecko API
CoinGecko is a cool website where you can go to check on the prices and statistics of pretty much every cryptocurrency there is. It’s fairly quick to use if you just need to check on one coin, but it can be fairly time-consuming if you need to check on multiple coins.
You can create a custom portfolio of coins, which is useful if you always want to see the same list of coins. But, it’s not so useful if you always want to check on different lists of coins. So, you might like to streamline the process a bit. For that, you can create a shell script that uses the CoinGecko Application Programming Interface (API).
To take full advantage of all of the CoinGecko API features, you’ll need to become a paying customer, which is rather expensive. Fortunately, you don’t need to do that for this demo. Instead, you’ll just use CoinGecko’s public API key, which is free-of-charge. To demo this, let’s do a hands-on lab.
Hands-on Lab — Creating the coingecko.sh Script
To begin, take a look at CoinGecko’s documentation page (https://www.coingecko.com/api/ documentation), and follow these steps as mentioned below:
-
Scroll down the page, and you’ll see a list of the various functions that you can perform with the public API. You can use the forms in the drop-down lists to create the code that you’ll copy into a shell script. I’ve already created the coingecko.sh shell script that performs three of those functions, which you can download from the Github repository. Before you use it though, you’ll need to ensure that the curl and jq packages are installed on your system. Anyway, here’s how the script works.
-
At the top of the gecko_api function, I defined the coin and currency variables as positional parameters 2. The if [ -z $coin ]; then line checks to see if the value of coin is zero length. If it is, it means that I haven’t entered any arguments when I invoked the script. So, it will then echo a series of statements about how to invoke the script.
-
Next, you see this elif stanza:
elif [ $coin == list ]; then curl -X 'GET' \ "https://api.coingecko.com/api/v3/coins/list?include_platform=true" \ -H 'accept: application/json' | jq | tee coinlist.txt- I copied this curl command from the CoinGecko documentation page, and pasted it into the script.
-
Then, I piped the output into the jq utility to convert the normal json output to pretty json format.
-
I then piped that output into tee in order to both view the output on screen and save it to a text file. Invoking the script with the list argument will download the entire list of coins that are supported by the API. The elif construct in the next stanza is the same as this elif construct, except that it will show a list of versus currencies that you can use for pricing the coins.
-
The else construct in the final stanza of the function requires you to enter both a coin and a versus currency as arguments. The original code from the documentation page contained the actual names of the coin and versus currency that I entered into the form on the documentation page. I changed them to the currency variables, respectively. I then had to change the pair of single quotes that surround the URL with a pair of double quotes, so that the $ in the variable names would be interpreted correctly.
-
Let’s say that you want to check the price of Bitcoin in US dollars. First, open the coinlist.txt file that you created when you ran the ./coingecko list command. Search for Bitcoin, and you’ll find a stanza that looks like this:
{ “id”: “bitcoin”, “symbol”: “btc”, “name”: “Bitcoin”, “platforms”: {} },
- Next, open the currency_list.txt that you created when you ran the ./coingecko currencies command. Scroll down until you find the versus currency that you want to use to price your particular coin or coins. Now, to view the price of your coin(s) in your desired currency, enter the “id:” value for the coin from the coinlist.txt file as the first argument, and the desired versus currency as the second argument, like this:
[donnie@fedora ~]$ ./coingecko.sh bitcoin usd% Total % Received % Xferd Average Speed Time Time TimeCurrentSpeedDload Upload Total Spent Left100 157 0 157 0 0 876 0 --:--:-- --:--:-- --:--:--- 872 { “bitcoin”: { “usd”: 34664, “usd_market_cap”: 675835016546.567, “usd_24h_vol”: 27952066301.047348, “usd_24h_change”: 2.6519150329293883, “last_updated_at”: 1698262594
- So, it looks like the current price of Bitcoin is $34664 US.
You can view multiple coins at a time by entering a comma-separated list, like this:
[donnie@fedora ~]$ ./coingecko.sh bitcoin,ethereum,dero usd% Total % Received % Xferd Average Speed Time Time TimeCurrent Dload Upload Total Spent LeftSpeed100 471 0 471 0 0 3218 0 --:--:-- --:--:-- --:--:--- 3226{ "bitcoin": { "usd": 34662, "usd_market_cap": 675835016546.567, "usd_24h_vol": 27417000940.815952, "usd_24h_change": 2.647099155664393, "last_updated_at": 1698262727 ... ...}[donnie@fedora ~]$- If you’re a trader, you might want to check the price of an altcoin in terms of some other versus currency, such as Bitcoin satoshis. Here, I’m checking the Bitcoin satoshi price of Dero:
[donnie@fedora ~]$ ./coingecko.sh dero sats% Total % Received % Xferd Average Speed Time Time TimeCurrent Dload Upload Total Spent LeftSpeed100 161 0 161 0 0 746 0 --:--:-- --:--:-- --:--:--- 748{ "dero": { "sats": 8544.47, "sats_market_cap": 106868665749.11504, "sats_24h_vol": 50996466.4091239, "sats_24h_change": -3.2533636291339687, "last_updated_at": 1698263552 }}-
So, the current satoshi price of Dero is 8544.47 sats. (Of course, these prices will be different by the time you look at them.)
-
The top three lines of the output are from the curl command that the script used to download information about the coins. For some strange reason, bash considers this curl message as an error message, even though it really isn’t. But, that’s actually good, because you can prevent having to see this message by using a stderr redirector at the end of your command, like this:
donnie@fedora:~$ ./coingecko.sh dero sats 2>/dev/null{ "dero": { "sats": 3389.23, "sats_market_cap": 42965410638.71136, "sats_24h_vol": 112468964.13986385, "sats_24h_change": 2.81262920882357, "last_updated_at": 1718482347 }}donnie@fedora:~$- Oh, I almost forgot about the most important part of the script, which is the command that calls the function:
gecko_api $1 $2It asks for two positional parameters, but will work just fine if you just enter either list or currencies as a single argument.
- Okay, this is good. But, what if you have a very long list of coins that you want to track, and you don’t want to type that whole long list in every time that invoke this script? Well, that’s easy. I’ll just create the mycoins.sh script, which will call the coingecko.sh script. Here’s how it looks:
#!/bin/bash./coingecko.sh bitcoin,dero,ethereum,bitcoin-cash,bitcoin-cash-sv,bitcoin-gold,radiant,monero usd 2>/dev/nullOf course, you can edit this script to add your own list of favorite coins.
- For a variation on this theme, download the coingecko-case.sh script, too. It’s the same script, but I built it with a case..esac construct instead of an if..then construct.
That’s about it for functions, at least for now. But, don’t be too surprised if you see more throughout the rest of this book.
Now, let’s wrap up and move on.
Summary
Functions are an important part of most every modern programming language. In this chapter I’ve shown you how to construct them, how to call them, and how to create function libraries that you can either use for yourself or share with other users.
In the next chapter, I’ll show you how to perform mathematical operations with shell scripts. I’ll see you there.
Questions
-
Which two of the following methods would you use to create a function? (Choose two.)
a. function function_name()
b. function_name()
c. declare -f function_name
d. declare -F function_name
-
You want to create a function that will pass the value of a variable back to the main program. Which of the following should you use to do that?
a. A global variable
b. A local variable
c. A return statement
d. A continue statement
-
You want to create a function that any user can use in his or her own scripts. What is the best way to do that?
a. Create a function library file in a central location, and make it executable.
b. Add the new functions to the /etc/bashrc file.
c. Create a function library file in a central location, but don’t make it executable.
d. D. Create a function library file in your own home directory.
-
Which two of the following commands would you use to reference a function library in your shell scripts? (Choose two.)
a. load
b. reference
c. source
d. .
-
You want to see the list of functions that are loaded into memory, along with their associated source code. Which command would you use?
a. declare -f
b. declare -F
c. debugger -f d. debugger -F
Further Reading
- Bash Functions: https://linuxize.com/post/bash-functions/
- Returning Values from Bash Functions: https://www.linuxjournal.com/content/return-values-bash-functions Bash Function & How to Use It {Variables, Arguments, Return}: https://phoenixnap.com/kb/bash-function Writing shell scripts-Lesson 15: Errors and Signals and Traps: http://linuxcommand.org/lc3_wss0150.php (Note that the author of this tutorial uses all upper-case letters for the names of scripting variables, which is something that I don’t advocate. Other than that, it’s a good tutorial.)
- Advance Bash Script Guide: https://tldp.org/LDP/abs/html/abs-guide.html#FUNCTIONS
Answers
- a and b
- b
- c
- c and d
- a
Join our community on Discord! Read this book alongside other users, Linux experts, and the author himself. Ask questions, provide solutions to other readers, chat with the author via Ask Me Anything sessions, and much more. Scan the QR code or visit the link to join the community. https://packt.link/SecNet