Max character length for Read command (input)

8,530

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.

Share:
8,530

Related videos on Youtube

Edmhar
Author by

Edmhar

Updated on September 18, 2022

Comments

  • Edmhar
    Edmhar over 1 year

    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.

  • Stéphane Chazelas
    Stéphane Chazelas almost 8 years
    Note that the read -d 5 counts the characters (not bytes, and if there are bytes not forming valid characters, you may get unexpected results) before the IFS trimming and after backslash processing. For insance, if you enter <space><space>abcd, it will store abc in $id, and if you enter \a\b\c\d\e, it will store abcde in $id. To avoid IFS trimming and backslash processing, use IFS= read -rn 5 id
  • Stéphane Chazelas
    Stéphane Chazelas almost 8 years
    Note that zsh has read -k n to read n characters (long before bash), but it's more like ksh93's read -N in that it will not stop at newline. Like for bash's read -n or ksh's read -n/N, if the input is coming from a terminal, the terminal is put out of the canonical mode, so bytes are sent as soon as they are entered, which also means things like backspace or ctrl-u won't work as usual.