HB Computer Security | Aide Memoire
  • Introduction
  • Core Technical Skills
    • Core Skills
      • Linux
        • Getting to Know Linux
          • Using the Shell
            • Shells, Terminals, and Virtual Consoles
            • Choose your Shell
            • Shell Commands
              • Non-PATH Commands
              • Command History
                • Command Line Editing
                  • Keystrokes for Navigating Command Lines
                  • Keystrokes for Editing Command Lines
                  • Keystrokes for Cutting and Pasting Text from within Command Lines
                • Command Line Recall
                  • Keystrokes for Command Line Recall
              • Connecting and Expanding Commands
                • Piping Between Commands
                • Sequential Commands
                • Expanding Commands
            • Shell Variables
              • Common Shell Variables
            • Aliases
            • Create your Own Shell Environment
              • Modification Ideas
          • Navigating the Linux File System (LFS)
            • Filesystem Commands
            • Listing Files and Directories
            • File Permissions and Ownership
              • Modifying Permissions with chmod
              • Modifying Default Permissions with umask
              • Change File Ownership with chown
            • Copying, Moving, and Removing Files
            • Finding Files
              • locate
              • find
              • grep
            • Downloading Files
              • axel
              • wget
              • curl
                • User-Agent: Googlebot
          • Working with Text Files
            • Using vim and vi to Edit Text Files
              • Starting with vi
              • Adding Text
              • Moving Around in the Text
            • Text Manipulation
        • System Administration
          • Installing Linux
            • Installing from Live Media
            • Installing in the Enterprise
            • Partitioning Hard Disks
              • Tips for Creating Partitions
          • Account Administration
            • The root Account
              • Becoming root with su
              • sudo
                • The /etc/sudoers File
                • Granting sudo privileges
                  • visudo Guidance
                • Useful sudo Hints
            • Other Administrative Accounts
            • Standard User Accounts
              • Risks of userdel: Orphaned Files
          • Graphical Remote Administration
            • Cockpit
              • Installation Guide
            • Remote Desktop Protocol with xrdp
              • Installation and Configuration
            • Remote Desktop with vnc
              • Installation and Configuration
              • Running VNC as a System Service
          • Managing Running Processes
            • Listing Processes
              • ps
              • top
              • htop
            • Backgrounding and Foregrounding
              • Starting a Background Process
              • Using Foreground and Background Commands
            • Killing and Recining Processes
              • kill and killall
          • Managing Software
            • Managing Software from the Desktop
            • Going Beyond the Limitations of Software Center
              • Debian Packages
                • Advanced Package Tool (apt)
                • Repositories
                • dpkg
        • Shell Scripting
          • Variables
            • Command Substitution
            • Arguments
          • Reading User Input
          • if, else, and elif
          • BOOLEAN Logic
          • Loops
            • for Loops
            • while Loops
          • Functions
          • Local Vs Global Variables
          • Summary
        • Securing Linux
      • Windows
        • Security Hardening
Powered by GitBook
On this page

Was this helpful?

  1. Core Technical Skills
  2. Core Skills
  3. Linux
  4. Shell Scripting

Functions

Previouswhile LoopsNextLocal Vs Global Variables

Last updated 3 years ago

Was this helpful?

However

When it comes to scripts, functions are basically Inception; a script within a script...

Functions are useful when we need to execute the same code multiple times. Rather than re-writing the same chunk of code over and over, we just write it once as a function and then call that function as needed. Put another way, a function is a subroutine, or a code block that implements a set of operations – a “black box” that performs a specified task.

Functions may be written in two different formats. The first format is more common to Bash scripts:

Function - typical bash syntax
function function_name {
commands...
}

However, bash will happily accept another format, which is likely more familiar to people who have experience programming in C:

Function - C-like syntax
function_name () {
commands...
}

For all intents and purposes, the formats are functionally identical and are a matter of personal preference. My recommendation is that you pick the once you prefer, or are most familiar with, and stick with it, but don't hop between the two...

So, let's look at a script where a function in created, and then called:

Function Call Example
#!/bin/bash

print_me () {
echo "You have been printed!"
}

print_me

Note that when a functioned is created, it will not execute unless it is explicitly called. Some script writers place all their functions at the very top of their scripts, and they are then called much further down as the need arises; This is where functions differ from the rest of the elements you will find in a typical script, which are executed sequentially from top to bottom.

However, a function MUST be placed in the script BEFORE it is called, or the call will fail.

Functions can also accept arguments, making them very versatile and therefore useful in our scripting:

Function call with command argument
#!/bin/bash

pass_arg () {
echo "Today's random number is: $1"
}

pass_arg $RANDOM

In this case, we passed a random number, $RANDOM, into the function, which outputs it as $1, the functions first argument. Note that the function definition (pass_arg()) contains parentheses. In other programming languages, such as C, these would contain the expected arguments, but in Bash the parentheses serve only as decoration. They are never used. Also note that the function definition (the function itself) must appear in the script before it is called. Logically, we can’t call something we have not defined.

In addition to passing arguments to Bash functions, we can of course return values from Bash functions as well. Bash functions do not actually allow you to return an arbitrary value in the traditional sense. Instead, a Bash function can return an exit status (zero for success, non-zero for failure) or some other arbitrary value that we can later access from the $? global variable. Alternatively, we can set a global variable inside the function or use command substitution to simulate a traditional return.

Hello Mr Charles...
Example of a function call in a bash script