Home > Pemrograman, Tutorial > Fungsi di Shell Bash

Fungsi di Shell Bash

Seperti halnya di bahasa pemrograman yang lain, di shell bash juga mengenal fitur fungsi. Fungsi (atau prosedur jika tanpa statemen return) berisi baris kode yang akan sering dipanggil/dijalankan oleh program (reusable code). Lebih lanjut, kode repetitif yang diimplementasikan dengan fungsi/prosedur akan memakan memori (dan harddisk) yang lebih sedikit dibandingkan jika kode tersebut masing-masing dituliskan ke dalam baris kode program yang membutuhkan, walaupun mengorbankan waktu eksekusi (dengan pemanggilan function call dari stack).

Bagaimana mengimplementasikan function dalam skrip bash? Berikut sedikit tutorial yang diambil dari ABS (advanced bash-scripting).

Deklarasi Fungsi

function function_name {
command
}

atau

function_name () {
command
}

Contoh:

  • function print_echo {
    echo "This is a function"
    }
  • print_echo() {
    echo "This is a function"
    }
  • Jika ditulis dalam satu baris, maka harus diakhiri dengan tanda ; (semicolon)
    function print_echo {echo "This is a function";}

Pemanggilan Fungsi

Fungsi di bash bisa dipanggil dalam kode utama atau dalam suatu fungsi lain dengan menuliskan nama fungsinya. Fungsi ini dianggap seperti perintah.

Contoh:

  • print_echo_1() {
    echo "This is a function #1"
    }
    print_echo_2() {
    echo "This is a function #2"
    print_echo_1 # Call print_echo_1
    }
    print_echo_1() # Call print_echo_2
    Tampilan yang akan muncul saat skrip dijalankan adalah:

    This is a function #2
    This is a function #1

Fungsi dengan Melewatkan Parameter

Contoh:

#!/bin/bash
# Functions and parameters
DEFAULT=default                             # Default param value.
func2 () {
   if [ -z "$1" ]                           # Is parameter #1 zero length?
   then
     echo "-Parameter #1 is zero length.-"  # Or no parameter passed.
   else
     echo "-Parameter #1 is \"$1\".-"
   fi
   variable=${1-$DEFAULT}                   #  What does
   echo "variable = $variable"              #+ parameter substitution show?
                                            #  ---------------------------
                                            #  It distinguishes between
                                            #+ no param and a null param.
   if [ "$2" ]
   then
     echo "-Parameter #2 is \"$2\".-"
   fi
   return 0
}
echo
echo "Nothing passed."
func2                          # Called with no params
echo
echo "Zero-length parameter passed."
func2 ""                       # Called with zero-length param
echo
echo "Null parameter passed."
func2 "$uninitialized_param"   # Called with uninitialized param
echo
echo "One parameter passed."
func2 first           # Called with one param
echo
echo "Two parameters passed."
func2 first second    # Called with two params
echo
echo "\"\" \"second\" passed."
func2 "" second       # Called with zero-length first parameter
echo                  # and ASCII string as a second one.
exit 0

Melewatkan Parameter dari Pemanggilan Skrip

Contoh:

#!/bin/bash
# func-cmdlinearg.sh
#  Call this script with a command-line argument,
#+ something like $0 arg1.
func () {
echo "$1"   # Echoes first arg passed to the function.
}           # Does a command-line arg qualify?
echo "First call to function: no arg passed."
echo "See if command-line arg is seen."
func
# No! Command-line arg not seen.
echo "============================================================"
echo
echo "Second call to function: command-line arg passed explicitly."
func $1
# Now it's seen!
exit 0

Melewatkan Referensi Tak Langsung

Contoh:

#!/bin/bash
# ind-func.sh: Passing an indirect reference to a function.
echo_var () {
echo "$1"
}
message=Hello
Hello=Goodbye
echo_var "$message"        # Hello
# Now, let's pass an indirect reference to the function.
echo_var "${!message}"     # Goodbye
echo "-------------"
# What happens if we change the contents of "hello" variable?
Hello="Hello, again!"
echo_var "$message"        # Hello
echo_var "${!message}"     # Hello, again!
exit 0

Dereferensi Parameter yang Dilewatkan ke Fungsi

Contoh:

#!/bin/bash
# dereference.sh
# Dereferencing parameter passed to a function.
# Script by Bruce W. Clare.
dereference ()
{
     y=\$"$1"   # Name of variable (not value!).
     echo $y    # $Junk
     x=`eval "expr \"$y\" "`
     echo $1=$x
     eval "$1=\"Some Different Text \""  # Assign new value.
}
Junk="Some Text"
echo $Junk "before"    # Some Text before
dereference Junk
echo $Junk "after"     # Some Different Text after
exit 0

Status Return

Contoh:

#!/bin/bash
# max.sh: Maximum of two integers.
E_PARAM_ERR=250    # If less than 2 params passed to function.
EQUAL=251          # Return value if both params equal.
#  Error values out of range of any
#+ params that might be fed to the function.
max2 ()             # Returns larger of two numbers.
{                   # Note: numbers compared must be less than 250.
if [ -z "$2" ]
then
  return $E_PARAM_ERR
fi
if [ "$1" -eq "$2" ]
then
  return $EQUAL
else
  if [ "$1" -gt "$2" ]
  then
    return $1
  else
    return $2
  fi
fi
}
max2 33 34
return_val=$?
if [ "$return_val" -eq $E_PARAM_ERR ]
then
  echo "Need to pass two parameters to the function."
elif [ "$return_val" -eq $EQUAL ]
  then
    echo "The two numbers are equal."
else
    echo "The larger of the two numbers is $return_val."
fi
exit 0

Redirection

Contoh:

  • #!/bin/bash
    # realname.sh
    #
    # From username, gets "real name" from /etc/passwd.
    ARGCOUNT=1       # Expect one arg.
    E_WRONGARGS=85
    file=/etc/passwd
    pattern=$1
    if [ $# -ne "$ARGCOUNT" ]
    then
      echo "Usage: `basename $0` USERNAME"
      exit $E_WRONGARGS
    fi
    file_excerpt ()    #  Scan file for pattern,
    {                  #+ then print relevant portion of line.
      while read line  # "while" does not necessarily need [ condition ]
      do
        echo "$line" | grep $1 | awk -F":" '{ print $5 }'
        # Have awk use ":" delimiter.
      done
    } <$file  # Redirect into function's stdin.
    file_excerpt $pattern
    # Yes, this entire script could be reduced to
    #       grep PATTERN /etc/passwd | awk -F":" '{ print $5 }'
    # or
    #       awk -F: '/PATTERN/ {print $5}'
    # or
    #       awk -F: '($1 == "username") { print $5 }' # real name from username
    # However, it might not be as instructive.
    exit 0
  • Function ()  # This works.
    {
      {
       echo $*
      } | tr a b
    }
    Function ()  # This doesn't work.
    {
      echo $*
    } | tr a b   # A nested code block is mandatory here.

Sumber

 

  • Advanced Bash-Scripting Guide: Chapter 24. Function

 

 

 

Categories: Pemrograman, Tutorial
  1. No comments yet.
  1. No trackbacks yet.
*

This blog is kept spam free by WP-SpamFree.

Skip to toolbar