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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like