Linux Classroom Series – 08/Sept/2020

Returning Text from functions

  • Look at the following script
return_using_globalvar() {
    return_value="How are you"

print_message() {
    echo "Message is ${input}"

return_text_by_echo() {
    echo "Message is ${input}"

# solution 1: Using global variables
echo "${return_value}"

# solution 2: Read the output
read -p "Enter your message "
return_test=$(return_text_by_echo "$REPLY")
echo "$return_test"

Recursive Functions

  • Function that calls itself is recursive functions

calculate_factorial() {
    if [ $1 -eq 1 ]
        echo 1
        local var=$(( $1 - 1 ))
        local res=$(calculate_factorial $var)
        echo $(( $res * $1 ))


read -p "Enter a number: " val
factorial=$(calculate_factorial $val)
echo "Factorial of $val is: $factorial"
  • Exercise:
  1. Write a function to download a file from internet to desired location
download_item "<url>" "<location>"
  1. Write a function to extract a tar to a specific location
untar_file <tar_location> <extract_location>

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin