检查一个string是否是回文

我试图检查一个string是否是在bash中的回文。 这是我想出来的:

#!/bin/bash read -p "Enter a string: " string if [[ $string|rev == $string ]]; then echo "Palindrome" fi 

现在, echo $string|rev给出反向string。 我的逻辑是在if的条件下使用它。 那并没有那么好。

那么,我怎样才能把“返回值”从一个variables存储起来呢? 或直接在一个条件使用它?

[[ ... ]]内没有echo和不必要的引用的另一种变化:

 #!/bin/bash read -p "Enter a string: " string if [[ $(rev <<< $string) == "$string" ]]; then echo Palindrome fi 

只有bash的实现:

 is_palindrome () { local word=$1 local len=$((${#word} - 1)) local i for ((i=0; i <= (len/2); i++)); do [[ ${word:i:1} == ${word:len-i:1} ]] || return 1 done return 0 } for word in hello kayak; do if is_palindrome $word; then echo $word is a palindrome else echo $word is NOT a palindrome fi done 

灵感来自gniourf_gniourf:

 is_palindrome() { (( ${#1} <= 1 )) && return 0 [[ ${1:0:1} != ${1: -1} ]] && return 1 is_palindrome ${1:1: 1} } 

我敢打赌,这个真正的递归调用的表现真的很糟糕。

使用$(command substitution)

 #!/bin/bash read -p "Enter a string: " string if [[ "$(echo "$string" | rev)" == "$string" ]]; then echo "Palindrome" fi