Avatar of magandrez

magandrez's solution

to Error Handling in the Bash Track

Published at Oct 28 2018 · 0 comments
Test suite


This exercise has changed since this solution was written.

Implement various kinds of error handling and resource management.

An important point of programming is how to handle errors and close resources even if errors occur.

This exercise requires you to handle various errors. Because error handling is rather programming language specific you'll have to refer to the tests for your track to see what's exactly required.

Run the tests with:

bats error_handling_test.sh

After the first test(s) pass, continue by commenting out or removing the skip annotations prepending other tests.

External utilities

Bash is a language to write scripts that works closely with various system utilities, like sed, awk, date and even other programming languages, like Python. This track does not restrict the usage of these utilities, and as long as your solution is portable between systems and does not require installing third party applications, feel free to use them to solve the exercise.

For an extra challenge, if you would like to have a better understanding of the language, try to re-implement the solution in pure Bash, without using any external tools.

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.


#!/usr/bin/env bash

@test "correct arguments" {
  run bash error_handling.sh Alice

  [ "$status" -eq 0 ]
  [ "$output" = "Hello, Alice" ]

@test "one long argument" {
  run bash error_handling.sh "Alice and Bob"

  [ "$status" -eq 0 ]
  [ "$output" = "Hello, Alice and Bob" ]

@test "incorrect arguments" {
  run bash error_handling.sh Alice Bob

  [ "$status" -ne 0 ]

@test "print usage banner with no value given" {
  run bash error_handling.sh

  [ "$status" -eq 1 ]
  [ "$output" = "Usage: ./error_handling <greetee>" ]
#!/usr/bin/env bash


error_handling() {
    echo "Usage: ./error_handling <greetee>"

greetings() {
    echo "Hello, $args"

if [ "$#" -eq 0 ]
    exit 1
elif [ "$#" -eq 1 ]
    exit 0
    exit 1

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?