Operating System‎ > ‎Linux‎ > ‎Linux Shell Script‎ > ‎

07. Functions (Part 2)

Variable Scope – Global Scope

  • Variables in a script have global scope by default
  • This means that any variable created in a function can be ‘seen’ and used by other functions in the script
  • For example, the following 2 functions both run without error
readID( )
{
       read –p “Enter ID: ” id # id is created here
}
printID( )
{
    echo “Your ID is $id” # id is accessed here
}
  • The only variables that have local scope (will change from function to function) are the positional parameters  $1, $2, $3, ..., $@
  • Global variables make it simpler for functions to share data, there is no need to pass data back and forth between functions

Variable Scope – Local Scope

  • Global variables can be dangerous when used in a library function, which typically is called by many different scripts
  • For example, we write a library function called fA:
    • fA ()  { temp=10; }
    • Since fA is a library function, it can be called from many different scripts that need fA’s functionality
  • Supposed someone has a script called scriptB that contains these lines of code:
temp=‘/etc/passwd’
fA
echo $temp
    • When scriptB runs, the value being printed will be: 10 and not /etc/passwd
    • This can make us unpopular with the callers of our fA function!
    • In this case, we want temp in fA to have local scope. This means that temp exists only when fA runs, and it is a different variable than any other temp variable that might be in use
  • To make a variable have local scope, use the local declaration:
local  varName
  • Examples:
fA ()  { local temp=10; } # temp is only for fA

OR

readID( )
{
    local id   # id can only be used by readID
    read –p “Enter ID: ” id
}

Function Usage

  • There are 3 common ways that functions are used
    • The function block appears at the begining of a script
    • The function can be called as many time as needed in the script, but the function is not available outside of the script
    • The function block is put in the ~/.bashrc file
      • When a shell first starts running, it reads the .bashrc file, and any function defined in this file is then ‘known’ to the shell
      • Any function defined in ~/.bashrc can be run on the command line
      • For example, in the .bashrc file is the function
        • goHome ( ) {  cd;  echo  At `pwd`;  }
        • On the command line:  goHome
        • will bring the user to the home directory, and the user’s current directory (home) path will be printed

  • The  function block is put in a text file
  • Before calling the function, the text file needs to be loaded into memory with the . operator
  • Then the function can be called on the command line
  • Example
$ cat fileA fileA has the function sayHi
sayHi ()
{
    echo Hi $USER
}

$ . fileA activate fileA

$ sayHi calling function sayHi
Hi testUser

Library of Functions

  • A library of functions is created by storing multiple function blocks in a text file
  • The text file becomes the library file
  • Once the library file is loaded into memory with the . operator, all functions in the library can be called individually on the command line
  • In a similar way, a script can also use the . operator to load the library file into memory and call functions in the library file
  • Example:
    • Assume fileA from the previous slide, with the function sayHi, we can have a scriptB:
$ cat scriptB
. fileA # activate fileA
sayHi # call function sayHi
    • Now run scriptB:
$ scriptB # run scriptB
Hi testUser # output of sayHi


The Here Document Introduction

  • There are times when the script needs to print multiple lines of text, such as instructions, to the user
  • There are 2 ways to do this
    • Use multiple echo commands in the script, one echo per line of text
    • Put all the lines of text into a text file, then use the cat command in the script to print the text file
  • A more convenient way is to merge the 2 ways above and use the here document. The here document is called this way because the text is here in the script itself
  • The here document is like a mini text file within the script
  • This mini text file is sent to the user through any command that can accept multiple input lines of text
  • For example
    • Use cat if you want to print the here document
    • Use mail if you want to email the here document 
    • Use grep if you want to select certain lines of the here document
  • Format:
command  <<  token
    text
    
    text
token
    • command is any utility that can accept multiple input lines of text
    • token is any symbol or string of your choice, but the 2 tokens at the start and the end must match
    • The << operator works like the input redirection operator < 
    • The start token must be on the same line as <<
    • The end token must be on a line by itself, and it must be at the beginning of the line
    • The shell sends everything between the start and end tokens to the command, and the command processes every line of text in the here document as if they are from a text file

The Here Document Examples

  • In a script, print instructions to the user
cat  << menu
    d: delete file
    p: print file
    q: quit
menu
  • From a script, email a short message to the user
mail $USER << msg
    start of script $0
    on $date by $USER
msg
  • From a script, select certain lines of the document based on user command line argument
grep $1 << +
    doctor 555-1234
    school 555-3456
    work 555-6789
+


Comments