How to set character limit on READ?

Hello,
I created the following (snippet from larger code):

 echo -n "A1: "
 read A1

 VERIFY=$(echo -n $A1|wc -c)
 if [ $VERIFY -gt 8 ]; then
  echo -e "TOO MANY CHARACTERS"
 fi

 echo -n "A2: "
 read A2
 echo -n "A3: "
 read A3
 echo -e "Concat: $B1/$B2/$B3"

Basically what it does is it asks the user for values for A1, A2, and A3. The only catch is that character length cannot exceed 8. I think I have the validations, but even if they exceed 8, the value is stored. How can I make it so that conditions for A1 must be met before you proceed. The same character limit applies to A2 and A3.

Use an infinite while loop. Break from the loop when the condition is met.

Here is a sample code:

#!/bin/ksh

while :
do
        print "A1: "
        read A1
        [ ${#A1} -le 8 ] && break
done

Use shell builtin to get variable length instead of wc

Thanks for the suggestion. Unfortunately, I have this in a bash script, so I'm trying to use bash.

That was just an example. Use bash instead, replace print with printf :

#!/bin/bash

while :
do
        printf "%s" "A1: "
        read A1
        [ ${#A1} -le 8 ] && break
done
1 Like

Could truncating it be a valid choice? If so, using typeset might be usful:-

typeset -L8 A1
read A1?"Please enter a string: "

You might end up with trailing blanks of the input is less that 8 characters though. Is that acceptable?

$ typeset -L8 A1 
$ read A1?"Please enter a string: "
Please enter a string: greatbiglongstring             
$ echo "!$A1!"                     
!greatbig!
$ read A1?"Please enter a string: "
Please enter a string: Hello
$ echo "!$A1!"                     
!Hello   !

I hope that this helps,
Robin
Liverpool/Blackburn
UK