Compare string length to a number

Hi,
I want to compare strings length to a number but i am getting error. I want first name should be length of 8.
Please help.

#bin !/bin/bash
clear
echo -n "Enter name "
read name
IFS=_
ary=($name)
for key in "${!ary[@]}"; do echo "$key${ary[$key]}"; done
##First name should be equal to 8 digits
var=${ary[0]}
l1=${#var}
echo "$l1"
if [ "$l1" == 8]
then 
echo "Length Matching"
else
echo "Not Matching"
if

Hello rajneesh4U,

As a starter, could you please change if [ "$l1" == 8] to if [[ "$l1" == 8 ]] and let us know how it goes then(Not tested complete script though).

Thanks,
R. Singh

Hi,
Still code is showing same error. I have changed below code as per your suggestion, but still not working.

#bin !/bin/bash
clear
echo -n "Enter name "
read name
IFS=_
ary=($name)
for key in "${!ary[@]}"; do echo "$key${ary[$key]}"; done
##First name should be equal to 8 digits
var=${ary[0]}
l1=${#var}

echo "$l1"

if [ ["$l1" == 8]]
then 
echo "Length Matching"
else
echo "Not Matching"
if

Merely posting that there are errors is not helping much.

  1. What errors do you get on running this script?
  2. What did you understand from the errors?
1 Like

Hi.

Does this help?

#!/bin/bash
#bin !/bin/bash
# clear
set -x
echo -n "Enter name "
read name
IFS=_
ary=($name)
for key in "${!ary[@]}"; do echo "$key${ary[$key]}"; done
##First name should be equal to 8 digits
var=${ary[0]}
l1=${#var}
echo "$l1"
if [ "$l1" == 8 ]
then 
echo "Length Matching"
else
echo "Not Matching"
# if
fi

See man bash for questions.

Bestr wishes ... cheers, drl

You jumped from the frying pan into the fire. if [ ["$l1" == 8]] is as wrong as if [ "$l1" == 8] is.

  • either needs a space after the 8
  • integer comparisons should be done with the -eq operator. While results are identical for single digit numbers, 100 would compare below 20 for string operations.
  • there should NOT be any space between the [[ .

Try

if [ "$l1" -eq 8 ]

or

[[ "$l1" -eq 8 ]]

.

1 Like

If you want to do what is in the comments:

##First name should be equal to 8 digits
case $var in 
  ([0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9])
    echo "The first part of name equals 8 digits"
  ;;
  (*)
    echo "The first part of name does not equal 8 digits"
esac

instead of $var you could also use ${name_*%%}

Or you could use:

case $name in 
  ([0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]_)
   echo "The first part of name equals 8 digits"
  ;;
  (*)
    echo "The first part of name does not equal 8 digits"
esac
1 Like

Hi.

Needing to compare $var to the pattern of digits, so could be:

if [[ "$var" =~ [0-9]{8} ]]

Best wishes ... cheers, drl

1 Like

In that case regex anchors would need to be used to ensure it begins with digits and/or that it is precisely 8 digits long..
for example (in recent bash / ksh93):

if [[ $var =~ ^[0-9]{8}$ ]]

or

if [[ $name =~ ^[0-9]{8}_ ]]
1 Like