Shell 正在尝试在bash中作为命令运行的赋值(str=$*)

Shell 正在尝试在bash中作为命令运行的赋值(str=$*),shell,palindrome,Shell,Palindrome,输入终端: cd Desktop chmod 777 isPalindromeFun.sh ./isPalindromeFun.sh isPalindrome madam 给出错误:str=madam未找到 #!/bin/bash function isPalindrome () { if [ "$#" -ne 0 ]; then inc=$1; # if it has arguments set the increment with the first argument fi [ $#

输入终端:

cd Desktop
chmod 777 isPalindromeFun.sh
./isPalindromeFun.sh
isPalindrome madam
给出错误:
str=madam未找到

#!/bin/bash

function isPalindrome () {
if [ "$#" -ne 0 ];
then
inc=$1; # if it has arguments set the increment with the first argument
fi

[ $# -eq 0 ] && { read str ;} || \ str=$*

String="$(echo $str | sed 's/[^[:alnum:]]//g' | \
tr '[:upper:]' '[:lower:]')"

if [ "$(echo $String | rev)" = "$String" ]
then
echo "\"$str\" is a palindrome"
else
echo "\"$str\" is not a palindrome"
fi
}

将其作为单行写入时,需要删除反斜杠:

[ "$#" -eq 0 ] && { read str ;} || \ str=$*
如果将代码编写为两行,则更有意义:

[ "$#" -eq 0 ] && { read str ;} || \
  str=$*
但是,在一行中,反斜杠只起到转义它后面的字符的作用——使下一个字符(空格)成为数据而不是语法——从而使您的命令

str=$*
相反,应该与

" str="$*
这意味着空间是命令的一部分。这不是一个有效的赋值,当然在您的系统上没有名为
“str=madam”
(以空格开头!)的命令



旁白:
$#
不需要严格引用——除非您将
IFS
设置为包含数字的值,扩展
$#
的结果肯定会扩展到一个单词——但我在这里这样做是为了解决StackOverflow的语法突出显示问题。

| |之后继续操作时,这
`有什么用吗?“这不是法律上的延续点吗?”埃坦雷斯纳,你说得很对——这就是为什么我说“会更有意义”,而不是说在那种情况下这是必要的。这至少会传达作者的意图。