Introduction to Bash Scripting
Alex Scriven
Data Scientist
If you have used functions in R or Python then you are familiar with these advantages:
Let's break down the function syntax:
A Bash function has the following syntax:
function_name () {
#function_code
return #something
}
You can also create a function like so:
function function_name {
#function_code
return #something
}
The main differences:
function
to denote starting a function buildCalling a Bash function is simply writing the name:
function print_hello () { echo "Hello world!" }
print_hello # here we call the function
Hello world!
Let's write a function to convert Fahrenheit to Celsius like you did in a previous lesson, using a static variable.
temp_f=30
function convert_temp () {
temp_c=$(echo "scale=2; ($temp_f - 32) * 5 / 9" | bc)
echo $temp_c }
convert_temp # call the function
-1.11
Introduction to Bash Scripting