Bash – Max character length for Read command (input)

bashreadshell-script

I have bash script that have input commands.

echo "Enter the id: " 
read id

I'd like to know if there's a way I can limit the character can I input in the for id. I mean example he can only enter 5 characters for id.

is that possible?

Thank you.

Best Answer

So with bash there are (at least) two options.

The first is read -n 5. This may sound like it meets your needs. From the man page

-n nchars
       read  returns after reading nchars characters rather than
       waiting for a complete line of input, but honor a  delim-
       iter  if fewer than nchars characters are read before the
       delimiter.

BUT there's a gotcha here. If the user types abcde then the read completes without them needing to press RETURN. This limits the results to 5 characters, but may not be a good user experience. People are used to pressing RETURN.

The second method is just to test the length of the input and complain if it's too long. We use the fact that ${#id} is the length of the string.

This results in a pretty standard loop.

ok=0

while [ $ok = 0 ]
do
  echo "Enter the id: " 
  read id
  if [ ${#id} -gt 5 ]
  then
    echo Too long - 5 characters max
  else
    ok=1
  fi
done

If you want it to be exactly 5 characters then you can change the if test from -gt to -eq.

Related Question