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.
We'll cover the following...
We'll cover the following...
Exercise
Write the following functions for printing error messages in English and German:
print_errorcode_to_error_encode_to_error_de
Write two versions of the “code_to_error” function:
- Using the case statement in
print-error-local.shfile. - Using an associative array in
print-error-array.shfile.
#!/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.