Skip to main content

Functions in Bash shell


Functions in Bash Scripting are a great way to reuse code. In this section you'll learn how they work and what you can do with them.
Think of a function as a small script within a script. It's a small chunk of code which you may call multiple times within your script. They are particularly useful if you have certain tasks which need to be performed several times. Instead of writing out the same code over and over you may write it once in a function then call that function every time.

Creating a function is fairly easy. They may be written in two different formats:

function_name () {
#code to execute
}
or
function function_name
{
#code to execute
}
The function can be called with just function_name

Example1:
f()
{
echo “This is a test function...f”
}
f
Example2:
function f
{
echo “This is a test function...f”
}
f
  • function_name: The name of the function.
  • Curly braces {}: Enclose the code block.
  • Functions are declared before being called.
 
Passing Arguments

It is often the case that we would like the function to process some data for us. We may send data to the function in a similar way to passing command line arguments to a script. We supply the arguments directly after the function name. Within the function they are accessible as $1, $2, etc.
Example:
f()
{
echo "first argument is=$1"
echo "second argument is= $2"
}
f first second # function call with arguments

Return Values
Most other programming languages have the concept of a return value for functions, a means for the function to send data back to the original calling location. Bash functions don't allow us to do this. They do however allow us to set a return status. Similar to how a program or command exits with an exit status which indicates whether it succeeded or not. We use the keyword return to indicate a return status.
Typically a return status of 0 indicates that everything went successfully. A non zero value indicates an error occurred.

We can use command substitution to return some value.
Example:
lines_in_file () {
cat $1 | wc -l
}
num_lines=$( lines_in_file file )
echo The file has $num_lines lines in it.

Variable scope
Scope refers to which parts of a script can see which variables. By default a variable is global. This means that it is visible everywhere in the script. We may also create a variable as a local variable. When we create a local variable within a function, it is only visible within that function. To do that we use the keyword local in front of the variable the first time we set it's value.
local var_name=value
It is generally considered good practice to use local variables within functions so as to keep everything within the function contained. This way variables are safer from being inadvertently modified by another part of the script which happens to have a variable with the same name (or vice versa). 

Example:
var_change ()
{
local var1='local 1'
echo Inside function: var1 is $var1 : var2 is $var2
var1='changed again'
var2='2 changed again'
}
var1='global 1'
var2='global 2'
echo Before function call: var1 is $var1 : var2 is $var2
var_change 
echo After function call: var1 is $var1 : var2 is $var2

output:
Before function call: var1 is global 1 : var2 is global 2
Inside function: var1 is local 1 : var2 is global 2
After function call: var1 is global 1 : var2 is 2 changed again

Menu Driven Program Using Functions
#!/bin/bash

# Function to display the menu
show_menu() {
    echo "1. Display Date"
    echo "2. List Files"
    echo "3. Show Disk Usage"
    echo "4. Exit"
}

# Function to handle menu choice
process_choice() {
    case $1 in
        1) date ;;
        2) ls ;;
        3) df -h ;;
        4) echo "Goodbye!"; exit 0 ;;
        *) echo "Invalid choice. Try again." ;;
    esac
}

# Main program
while true; do
    show_menu
    read -p "Enter your choice: " choice
    process_choice $choice
done

Recursive Functions
Bash functions can call themselves, but recursion should be used cautiously to avoid infinite loops.
#!/bin/bash

# Factorial function
factorial() {
    if [ $1 -le 1 ]; then
        echo 1
    else
        local prev=$(factorial $(( $1 - 1 )))
        echo $(( $1 * prev ))
    fi
}

# Call the function
result=$(factorial 5)
echo "Factorial of 5 is: $result"

Function with Default Arguments

Bash does not support default arguments natively, but you can handle them manually.

#!/bin/bash
# Function with default argument handling
greet() {
local name=${1:-"User"} # Use "User" if no argument is provided
echo "Hello, $name!"
}

greet "Alice"
greet
Output
Hello, Alice!
Hello, User!

Key Points

  1. Arguments: Passed as $1, $2, etc. $@ holds all arguments.
  2. Local Variables: Use local to avoid variable name clashes.
  3. Returning Values: Use return for status codes, and echo for output.
  4. Calling Functions: Functions must be defined before being called.

Comments

Popular posts from this blog

Writing a Bash Shell Script

Bash shell scripts in Linux are text files that contain a series of commands that can be executed by the Bash shell. Bash (Bourne Again Shell) is a popular shell in Linux and UNIX systems, and shell scripts are used to automate tasks, configure systems, or perform a sequence of operations. How to Write a Bash Shell Script Create a New File: You can create a new script using any text editor like nano , vim , or gedit . gedit myscript.sh Write the Script: A basic shell script begins with a "shebang" ( #!/bin/bash ) to specify the interpreter that will be used to execute the script. The rest of the file contains the commands to be run. Example of a simple script: #!/bin/bash # This is a comment echo "Hello, World!" # Print "Hello, World!" #!/bin/bash : Specifies that the script will be executed using the Bash shell. echo "Hello, World!" : A command that prints the string "Hello, World!" to the terminal. Comments: Any line starting ...

Basic Linux Commands For Beginner's

Basic Linux Commands for Beginners Linux is an Operating System’s Kernel. You might have heard of UNIX. Well, Linux is a UNIX clone. But it was actually created by Linus Torvalds from Scratch. Linux is free and open-source, that means that you can simply change anything in Linux and redistribute it in your own name! There are several Linux Distributions, commonly called “distros”. A few of them are: Mint Ubuntu Linux Red Hat Enterprise Linux Debian Fedora Kali Linux is Mainly used in Servers. About 90% of the Internet is powered by Linux Servers. This is because Linux is fast, secure, and free! The main problem of using Windows Servers are their cost. This is solved by using Linux Servers. Forgot to mention, the OS that runs in about 80% of the Smartphones in the World, Android, is also made from the Linux Kernel. Yes, Linux is amazing! A simple example of its security is that most of the viruses in the world run on Windows, but not on Linux...

Different syntax for writing arithmetic expressions in bash shell

#!/bin/bash echo "Enter two numbers" read a b s=`expr $a + $b` echo "Sum1=$s" s=$[$a+$b] echo "sum2=$s" ((s=$a+$b)) echo "sum3=$s" ((s=a+b)) echo "sum3=$s" let s=$a+$b echo "sum4=$s" let s=a+b echo "sum4=$s" Note:bash shell support only integer arithmetic.zsh support operations on real numbers.We can use bc in bash shell to do real arithmetic. Eg: echo "$a*$b"|bc # where a and b are real Mathematical Operators With Integers Operator Description Example Evaluates To + Addition echo $(( 20 + 5 )) 25 - Subtraction echo $(( 20 - 5 )) 15 / Division echo $(( 20 / 5 )) 4 * Multiplication echo $(( 20 * 5 )) 100  % Modulus echo $(( 20 % 3 )) 2 ++ post-increment (add variable value by 1) x=5 echo $(( x++ )) echo $(( x++ )) 5 6 -- post-decrement (subtract variable value by 1) x=5 echo $(( x-- )) 4 ** Exponentiation x=2 y=3 echo $(( x ** y )) 8