Avatar of tivasyk

tivasyk's solution

to Error Handling in the Bash Track

Published at Dec 10 2018 · 0 comments
Instructions
Test suite
Solution

Note:

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.

error_handling_test.sh

#!/usr/bin/env bash

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

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

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

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

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

  [ "$status" -ne 0 ]
}

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

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

show_help() {
    # This could be useful to mention $NAME (script name) in the help text:
    # local NAME=$(basename $0)
    cat <<EOF
Usage: ./error_handling <greetee>
EOF
}

main() {
    if [ $# -ne 1 ]; then
        show_help
        exit 1
    fi

    echo "Hello, ${1}"
}

main "$@"

Community comments

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

tivasyk's Reflection

This may seem a bit too overcomplicated for such a simple task... I was just trying to prepare a "template" script for some real life case, when several pages of usage help could be required, which would be very cumbersome if done with echo's.