🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of linuxleep

linuxleep's solution

to Reverse String in the Bash Track

Published at Jul 30 2020 · 2 comments
Instructions
Test suite
Solution

Note:

This exercise has changed since this solution was written.

Reverse a string

For example: input: "cool" output: "looc"

Run the tests with:

bats reverse_string_test.sh

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

Source

Introductory challenge to reverse an input string https://medium.freecodecamp.org/how-to-reverse-a-string-in-javascript-in-3-different-ways-75e4763c68cb

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.

reverse_string_test.sh

#!/usr/bin/env bash

@test "An empty string" {
  #skip
  run bash reverse_string.sh ""

  [ "$status" -eq 0 ]
  [ "$output" = "" ]
}

@test "A word" {
  skip
  run bash reverse_string.sh "robot"

  [ "$status" -eq 0 ]
  [ "$output" = "tobor" ]
}

@test "A capitalised word" {
  skip
  run bash reverse_string.sh "Ramen"

  [ "$status" -eq 0 ]
  [ "$output" = "nemaR" ]
}

@test "A sentence with punctuation" {
  skip
  run bash reverse_string.sh "I'm hungry!"

  [ "$status" -eq 0 ]
  [ "$output" = "!yrgnuh m'I" ]
}

@test "A palindrome" {
  skip
  run bash reverse_string.sh "racecar"

  [ "$status" -eq 0 ]
  [ "$output" = "racecar" ]
}
#!/usr/bin/env bash

main() {
    echo $@ | rev
    exit 0
}

main "$@"

Community comments

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

Learned something new.

rev

Clever solution.

Avatar of linuxleep

Thank you. When I ran across it the first time it made me wish I had seen it sooner. Now, I just wish it was in all the languages.

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?