Search code examples
bashshellsh

Syntax error for (( $word = "y" || $word = ""Y" ))


This is my shell script where i check whether the entered word is y or n; if any of these match then it will print an appropriate message.

 #! /bin/bash

read word

if (( $word = "y" || $word = "Y" ))
then    
    echo "YES"
elif (( $word = "n" || $word = "N" ))
then    
    echo "NO"
fi

But when I run this code then it will give me a run-time error.

Solution.sh: line 5: ((: y = y || y = Y : attempted assignment to non-variable (error token is "= Y ")
Solution.sh: line 8: ((: y = n || y = N : attempted assignment to non-variable (error token is "= N ")

Solution

  • You want [[ ... ]], not ((...)) (which is for arithmetic expressions)

    #!/bin/bash
    
    read word
    
    if [[ $word = "y" || $word = "Y" ]]
    then    
        echo "YES"
    elif [[ $word = "n" || $word = "N" ]]
    then    
        echo "NO"
    fi
    

    You can simplify this using pattern matching rather than strict equality testing

    if [[ $word = [Yy] ]]
    then
        echo "YES"
    elif [[ $word = [Nn] ]]
    then
        echo "NO"
    fi
    

    Or use a standard case statement

    case $word in
      [Yy]) echo "YES" ;;
      [Nn]) echo "NO" ;;
    esac