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
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
#!/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
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.
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
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):