How to Reverse a String in Bash Script?

I have a string like that:

|abcdefg|

and I want to reverse this String

gfedcba

Is that possible in bash?

5

1 Answer

With rev command you can reverse the string:

$ echo '|abcdefg|' |rev
|gfedcba|

if you want pure bash solution:

str='|abcdefg|'; for ((i=${#str}-1; i>=0; i--));do printf "${str:$i:1}"; done
  • ${#str} returns the character length of its parameter str.
  • ${str:start:length} picks length characters from its parameter str from start point (the first character has index 0).

if you don't want first & last pipe characters, do:

str='|abcdefg|'; for ((i=${#str}-2; i>=1; i--));do printf "${str:$i:1}"; done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest