0
read -p "Input a sentence: " mystring
string=("$mystring" | rev)
echo "The sentence reversed character by character is: " $string

I want to reverse only $string but it reverses everything before $string to. Can someone help me pls?

  • 2
    You are trying to run $mystring as a command. Try $(echo $mystring | rev) for better results. It would also help to give a sample input and expected output. – doneal24 Oct 25 '21 at 19:13

1 Answers1

3

You need to feed the string as standard input to rev, either using a herestring or heredoc or by piping the output of printf and then collect the output of rev using command substitution.

IFS= read -rep 'Input a sentence: ' mystring

string=$( rev <<< "$mystring" )

or:

string=$( printf '%s\n' "$mystring" | rev )

printf '%s\n' "The sentence reversed character by character is: $string"

Note that rev is not a standard command (though is pretty common). Had you used zsh instead of bash, you could have done the reversing internally (and also be able to let the user enter anything):

mystring=
vared -p 'Input a sentence: ' mystring
string=${(j[])${(s[]Oa)mystring}}
print -r The sentence reversed character by character is: $string

(note that since zsh's vared, as opposed to bash's read -e allows the user to include newline characters (and any character, even NUL) in the contents of the var that is edited, using rev to reverse it would not work as rev works on one line at a time).

In bash, remember: