Search code examples
shellpalindrome

Assignment (str=$*) trying to run as a command in bash


input in terminal:

cd Desktop
chmod 777 isPalindromeFun.sh
./isPalindromeFun.sh
isPalindrome madam

gives an error: str=madam not found

#!/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
}

Solution

  • The backslash needs to be removed when writing this as a single line:

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

    It would make more sense if writing the code as two lines:

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

    On just one line, however, the backslash only has the effect of escaping the character following it -- making that next character, a space, be data rather than syntax -- and thus makes your command

    str=$*
    

    instead be the same as

    " str="$*
    

    meaning the space is part of the command. That's not a valid assignment, and of course there's no command called " str=madam" (starting with a space!) on your system.


    Aside: $# doesn't strictly need to be quoted -- unless you have IFS set to a value that contains numbers, the results from expanding $# are guaranteed to expand to a single word -- but I'm doing so here as a workaround for StackOverflow's syntax highlighting.