Introduction to Bash Scripting
Alex Scriven
Data Scientist
Passing arguments into functions is similar to how you pass arguments into a script. Using the $1
notation.
You also have access to the special ARGV
properties we previously covered:
$1
, $2
notation.$@
and $*
give all the arguments in ARGV
$#
gives the length (number) of argumentsLet's pass some file names as arguments into a function to demonstrate. We will loop through them and print them out.
function print_filename { echo "The first file was $1"
for file in $@ do echo "This file has name $file" done }
print_filename "LOTR.txt" "mod.txt" "A.py"
The first file was LOTR.txt
This file has name LOTR.txt
This file has name mod.txt
This file has name A.py
'Scope' in programming refers to how accessible a variable is.
Why does this matter? If you try and access something that only has local scope - your program may fail with an error!
Unlike most programming languages (eg. Python and R), all variables in Bash are global by default.
function print_filename { first_filename=$1 }
print_filename "LOTR.txt" "model.txt" echo $first_filename
LOTR.txt
Beware global scope may be dangerous as there is more risk of something unintended happening.
You can use the local
keyword to restrict variable scope.
function print_filename { local first_filename=$1 }
print_filename "LOTR.txt" "model.txt" echo $first_filename
Q: Why wasn't there an error, just a blank line?
Answer: first_filename
got assigned to the global first ARGV element ($1
).
I ran the script with no arguments (bash script.sh
) so this defaults to a blank element. So be careful!
We know how to get arguments in - how about getting them out?
The return
option in Bash is only meant to determine if the function was a success (0) or failure (other values 1-255). It is captured in the global variable $?
Our options are:
echo
what we want back (last line in function) and capture using shell-within-a-shellLet's see a return error:
function function_2 { echlo # An error of 'echo' }
function_2 # Call the function echo $? # Print the return value
script.sh: line 2: echlo: command not found
127
What happened?
$?
was 127 (error)Let's correctly return a value to be used elsewhere in our script using echo
and shell-within-a-shell capture:
function convert_temp { echo $(echo "scale=2; ($1 - 32) * 5 / 9" | bc) }
converted=$(convert_temp 30) echo "30F in Celsius is $converted C"
30F in Celsius is -1.11 C
Introduction to Bash Scripting