if a variable is being declared in a function, it can be used globally only after the function is called
eg
#!/bin/bashmy_function () { GLOBAL_VAR=1}# GLOBAL_VAR not available yetecho $GLOBAL_VAR# calling the functionmy_function# GLOBAL_VAR is available nowecho $GLOBAL_VAR
local variables declared using the local keyword
only functions can have local variables
it is best practice to keep variables local in functions
local LOCAL_VAR=1
Exit Statuses in Functions
functions are like shell scripts in shell scripts
explicitly
return <RETURN_CODE
implicitly
exit status is that of the last command executed in the function
range from 0 to 255
$? is exit status of last function
my_functionecho "$?"
eg
#!/usr/bin/bashfunction backup_file() { if [ -f $1 ] then BACK="/tmp/$(basename ${1}).$(date +%F).$$" # $$ is the PID of the script echo "Backing up $1 to{BACK}" cp $1 $BACK fi}backup_file /etc/hostsif [ $? -eq 0 ]then echo "Backup Succeeded"fi
better version eg
#!/usr/bin/bashfunction backup_file () { if [ -f $1 ] then local BACK="/tmp/$(basename ${1}).$(date +%F).$$" echo "Backing up $1 to $BACK" cp $1 $BACK else return 1 fi}
Practice
Exercise 1:
Write a shells script that consists of a function that displays the number of files in the present working directory. Name this function “file_count” and call it in your script. If you use a variable in your function, remember to make it local.
Hint: the wc utility is used to count the number of lines, words, and bytes
Exercise 2:
Modify the script from the previous exercise. Make the “file_count” function accept a directory as an argument. Next have the function display the name of the directory followed by a colon. Finally display the number of files to the screen on the next line. Call the function three times. First on /etc, then on /var, then on /usr/bin
My Solution
#!/usr/bin/bash# script to count files/directories in a folderfunction file_count () { local FILES=$(ls $1) echo "${1}:" echo " $(echo "$FILES" | wc -w)"}for i in {1..3}do read -p "Enter a path: " DIR file_count $DIRdone
> Enter a path: /etc
> /etc:
> 163
> Enter a path: /var
> /var:
> 13
> Enter a path: /usr/bin
> /usr/bin:
> 3005
Given Solution
#!/bin/bashfunction file_count() { local DIR=$1 local NUMBER_OF_FILES=$(ls $DIR | wc -l) echo "${DIR}:" echo "$NUMBER_OF_FILES"}file_count /etcfile_count /varfile_count /usr/bin