Bash Shell Script Function Examples

How do I create a shell script function using Bash under UNIX / Linux operating systems?

Functions are nothing but small subroutines or subscripts within a Bash shell script. You need touse to break up a complex script into separate tasks. This improves overall script readability and ease of use. However, shell function cannot return value. They return a status code.

Declare Shell Function

All functions must be declared before they can be used. The syntax is:

function name(){


 return $TRUE

You can call function by typing its name:



Create a shell script called

# a sample shell script to demonstrate the concept of Bash shell functions
# define usage function
	echo "Usage: $0 filename"
	exit 1
# define is_file_exits function 
# $f -> store argument passed to the script
	local f="$1"
	[[ -f "$f" ]] && return 0 || return 1
# invoke  usage
# call usage() function if filename not supplied
[[ $# -eq 0 ]] && usage
# Invoke is_file_exits
if ( is_file_exits "$1" )
 echo "File found"
 echo "File not found"

Run it as follows:
chmod +x
./ /etc/resolv.conf

Task: Export functions

You need to use export command:

  echo "Foo"
export -f fname

Task: Make readonly functions

You create functions at the top of the script and set the readonly attribute with the readonly command:

  echo "Foo"
  echo "Usage: $0 foo bar"
  exit 1
readonly -f usage
readonly -f fname

Task: Local variables functions

Use the local command to create local variables:

# gloabal x and y
  # local variable x and y with passed args	
  local x=$1
  local y=$2
  echo $(( $x + $y ))
echo "x: $x and y: $y"
# call function 
echo "Calling math() with x: $x and y: $y"
math 5 10
# x and y are not modified by math()
echo "x: $x and y: $y after calling math()"
echo $(( $x + $y ))

Task: Recursion

A recursive function call itself. Recursion is a useful technique for simplifying some complex algorithms, and breaking down complex problems.

  # do something
  # if not false call foo
# call foo

See Recursive function for more details.

Recommend readings:
🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 9 comments so far... add one

CategoryList of Unix and Linux commands
Disk space analyzersdf duf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Modern utilitiesbat exa
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg glances gtop jobs killall kill pidof pstree pwdx time vtop
Searchingag grep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
9 comments… add one
  • shweta Oct 26, 2012 @ 7:34
    fun1(){ x=100000;  echo " In fun() x = $x " ; }
    fun2(){ y=200000;  echo " In fun() y = $y " ; }
    x=100 ; y=200
    echo "before calling d fun1() x=$x" 
    echo -e $(fun1)
    echo " after calling d fun1() x=$x"
    echo "before calling d fun2() y=$y" 
    echo " after calling d fun() y=$y"

    output :

    before calling d fun1() x=100
    In fun() x = 100000
     after calling d fun1() x=100
    before calling d fun2() y=200
     In fun() y = 200000
     after calling d fun() y=200000

    I m a beginner in Shell programing…., anybody can explain me what is the diff. b/w calling a function as $(fun) or fun….., why the value of x is not changed n value of is changed… what is diff. b/w both invocation.

  • unop Dec 23, 2012 @ 5:07


    $(command) – causes the command to be run in a subshell (child process of the parent) and any changes made in the subshell do not affect the parent execution context. See the section COMMAND EXECUTION ENVIRONMENT in the bash manpage.

    x=1; echo “before x=$x”; echo “$x” | while read x; do echo “during x=$x”; ((x++)); echo “during x=$x”; done; echo “after x=$x”
    before x=1
    during x=1
    during x=2
    after x=1

    x=1; echo “before x=$x”; ( x=2; echo “during x=$x”; ); echo “after x=$x”
    before x=1
    during x=2
    after x=1

  • unop Dec 23, 2012 @ 5:09


    commands should be defined (as per `help function’) using one of the following syntaxes

    function funcname { … }
    funcname() { … }

    definitely not
    function funcname() { … }

  • Newbie Mar 3, 2013 @ 0:19


    Thanks sir, this is explicated in detail and simply, you learn me function with bash :)

    Have a good time

  • Jordan May 3, 2013 @ 14:59

    So helpfull as usually…

  • Ting Jul 2, 2013 @ 13:55

    Can’t functions take in variable? As $1… .

  • Lewis Stevens Jun 24, 2015 @ 19:49

    Hello, i seem to be having this issue whenever i try to do bash on centos. I don’t know why as my bash is /bin/bash and ive tried it on many new installs in this code… i used the code from this section: Task: Local variables functions.

    [root@SERVER01 /]# sh
    :command not found
    ` line 6: syntax error near expected token `{
    ` line 6: `math(){

    Its really annoying.. i always get :command not found with any new lines… and functions always create an error aswell… why is this?


  • kamil Dec 31, 2015 @ 14:26

    how can I pass the argument to the loop? I have the following code:

          rm $HOME/.netrc
          echo "machine server login password password" >$HOME/.netrc      
          echo "macdef Ka" >>$HOME/.netrc
          echo "prompt" >>$HOME/.netrc
          for yyyy in {$1..$2}
          for mm in {$3..$4}
          for day in {$5..$6}
          echo "cd /gpmdata/$yyyy/$mm/$day/radar" >> $HOME/.netrc
          echo "bye" >> $HOME/.netrc
          echo "" >> $HOME/.netrc
          chmod 600 $HOME/.netrc
          echo '$a' | ftp  #I don't know if this line is correct
    GPM_download $1 $2 $3 $4 $5 $6 $7
    exit 1

    then I execute

    ./ 2014 2014 05 05 27 27 Ka
    but the created file .netrc looks like this

    "cd /gpmdata/{2014..2014}/{05..05}/{27..27}/radar"

    not as I wish “cd /gpmdata/20140527/radar”

  • Manpreet Jul 30, 2016 @ 14:55

    How we written commands to run any function in command prompt

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum