Search⌘ K
AI Features

Exercise: Functions

Explore how to write Bash functions that handle error messages in multiple languages. Learn to use case statements and associative arrays to avoid code duplication and manage localization based on system settings. This exercise strengthens your understanding of function design, variable scope, and efficient scripting in Bash.

Exercise

Write the following functions for printing error messages in English and German:

  • print_error
  • code_to_error_en
  • code_to_error_de

Write two versions of the “code_to_error” function:

  • Using the case statement in print-error-local.sh file.
  • Using an associative array in print-error-array.sh file.
#!/bin/bash

code_to_error_de()
{
  # your code
}

code_to_error_en()
{
  # your code
}

print_error()
{
  # your code
}


# Calling the function
print_error 1 "readme.txt"

Solution

Using case statement

Let’s combine the code of the code_to_error and print_error functions into one file.

 ...