Let us see how to pass parameters to a Bash function.
Contents
function_name(){
command_block
}
## OR ##
function function_name_here(){
command_line_block
}
## passing parameters to a Bash function ##
my_function_name(){
arg1=$1
arg2=$2
command on $arg1
}
my_function_name foo bar
Where,
Create a function called fresh.sh:
#!/bin/bash
# write a function
fresh(){
# t stores $1 argument passed to fresh()
t=$1
echo "fresh(): \$0 is $0"
echo "fresh(): \$1 is $1"
echo "fresh(): \$t is $t"
echo "fresh(): total args passed to me $#"
echo "fresh(): all args (\$@) passed to me -\"$@\""
echo "fresh(): all args (\$*) passed to me -\"$*\""
}
# invoke the function with "Tomato" argument
echo "**** calling fresh() 1st time ****"
fresh Tomato
# invoke the function with total 3 arguments
echo "**** calling fresh() 2nd time ****"
fresh Tomato Onion Paneer
Save and close the file. Run it as follows:
chmod +x fresh.sh
./fresh.sh
Sample outputs:
**** calling fresh() 1st time ****
fresh(): $0 is ./fresh.sh
fresh(): $1 is Tomato
fresh(): $t is Tomato
fresh(): total args passed to me 1
fresh(): all args ($@) passed to me -"Tomato"
fresh(): all args ($*) passed to me -"Tomato"
**** calling fresh() 2nd time ****
fresh(): $0 is ./fresh.sh
fresh(): $1 is Tomato
fresh(): $t is Tomato
fresh(): total args passed to me 3
fresh(): all args ($@) passed to me -"Tomato Onion Paneer"
fresh(): all args ($*) passed to me -"Tomato Onion Paneer"
Let us try one more example. Create a new shell script to determine if given name is file or directory (cmdargs.sh):
#!/bin/bash
# Name - cmdargs.sh
# Purpose - Passing positional parameters to user defined function
# -----------------------------------------------------------------
file="$1"
# User-defined function
is_file_dir(){
# $f is local variable
local f="$1"
# file attributes comparisons using test i.e. [ ... ]
[ -f "$f" ] && { echo "$f is a regular file."; exit 0; }
[ -d "$f" ] && { echo "$f is a directory."; exit 0; }
[ -L "$f" ] && { echo "$f is a symbolic link."; exit 0; }
[ -x "$f" ] && { echo "$f is an executeble file."; exit 0; }
}
# make sure filename supplied as command line arg else die
[ $# -eq 0 ] && { echo "Usage: $0 filename"; exit 1; }
# invoke the is_file_dir and pass $file as arg
is_file_dir "$file"
#function