user6205450
user6205450

Reputation:

Linux Script error with comparing strings

i'm trying to take two string input and check if they are equal or not, if not equal then tell the character length. i'm getting not found error after i type two strings, can someone tell what am i doing wrong? i tried using:

    #!/bin/bash
    while true; do
    echo "Please Enter two name to compare"
    read name_1 name_2
    1=${#name_1}
    2=${#name_2}

    if [ "$name_1" -eq  "$name_2" ] 
    then
      echo "$name_1 and $name_2 are equal"
    else
      echo "$name_1 and $name_2 are not equal"
    fi 
    echo "String 1 length is $(1)"            
    echo "String 2 length is $(2)"

    done

Upvotes: 1

Views: 627

Answers (3)

Reto
Reto

Reputation: 1343

This one will work exactly as expected:

#!/bin/bash
while true; do
echo "Please Enter two name to compare"
read name_1 name_2
one=${#name_1}
two=${#name_2}

if [ "$name_1" = "$name_2" ]
then
  echo "$name_1 and $name_2 are equal"
else
  echo "$name_1 and $name_2 are not equal"
fi 
echo "String 1 length is $one"            
echo "String 2 length is $two"

done

Upvotes: 1

tale852150
tale852150

Reputation: 1628

Try the following. I used [[ ]] around your if and changed the variables from 1 and 2 to x and y:

#!/bin/bash
while true; do
    echo "Please Enter two name to compare"
    read name_1 name_2
    x=${#name_1}
    y=${#name_2}

    if [[ "$name_1" == "$name_2" ]]
    then
      echo "$name_1 and $name_2 are equal"
    else
      echo "$name_1 and $name_2 are not equal"
    fi
    echo "String 1 length is $x"
    echo "String 2 length is $y"

done
exit

Upvotes: 0

heemayl
heemayl

Reputation: 41987

Points:

  • A user defined variable in bash can not start with a digit and so obviously can not only be a digit

  • -eq does arithmetic comparison; as you are comparing strings use = (POSIX) or ==

Upvotes: 1

Related Questions