Max character length for Read command (input) Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Max character length for Read command (input) without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.


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

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.


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

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

We are here to answer your question about Max character length for Read command (input) - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji