Avatar of tivasyk

tivasyk's solution

to Two Fer in the Bash Track

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

Two-fer or 2-fer is short for two for one. One for you and one for me.

"One for X, one for me."

When X is a name or "you".

If the given name is "Alice", the result should be "One for Alice, one for me." If no name is given, the result should be "One for you, one for me."

Run the tests with:

bats two_fer_test.sh

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

Source

https://en.wikipedia.org/wiki/Two-fer

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.

two_fer_test.sh

#!/usr/bin/env bash

@test "no name given" {
  #skip
  run bash two_fer.sh
  [ "$status" -eq 0 ]
  [ "$output" == "One for you, one for me." ]
}

@test "a name given" {
  skip
  run bash two_fer.sh Alice
  [ "$status" -eq 0 ]
  [ "$output" == "One for Alice, one for me." ]
}

@test "another name given" {
  skip
  run bash two_fer.sh Bob
  [ "$status" -eq 0 ]
  [ "$output" == "One for Bob, one for me." ]
}
#!/bin/bash
# tivasyk <tivasyk@gmail.com>

main() {
    input=$*
    output="One for X, one for me."

    if [ -z "$input" ]; then
        output=${output/"X"/"you"}
    else
        output=${output/"X"/"$input"}
    fi

    echo "${output}"
}

main "$@"

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?