0

Is there anyway to check for a valid username input in bash? For example, using the read command is there a way to ignore or interpret the left arrow input instead of storing ^[[D in the variable? What other input method can be used in bash other than read?

4
  • 1
    There are ways to 2 read a line: using character by character, or using readline. Most modern read implementations use the readline library, which internally takes care of interpreting left arrow as cursor movement and not literal^[[D. Commented Jul 16, 2019 at 4:37
  • 1
    Sorry, I was wrong. read uses readline only when it is passed the -e option; as answered by Amadan. Commented Jul 16, 2019 at 4:46
  • @anishsane No problem, can you provide more info/documentation on the character by character method? Commented Jul 16, 2019 at 4:51
  • 1
    For character by character, you will need to implement minimal version of readline yourself. Too much pain, if you ask me. Easier would be throwing an error after the user presses enter. Commented Jul 16, 2019 at 4:54

1 Answer 1

3

read -e will interpret arrows correctly. From man bash:

-e If the standard input is coming from a terminal, readline (see READLINE above) is used to obtain the line. Readline uses the current (or default, if line editing was not previously active) editing settings.

Checking whether an input string is a valid username is your responsibility, as it has nothing to do with inputting (e.g. see Check Whether a User Exists)

Sign up to request clarification or add additional context in comments.

2 Comments

How can we check characters one by one to confirm that no / character is entered while using the read method?
"while using the read method" - you can't. Again, nothing to do with inputting. You can check it later. See How to check if a string contains a substring in Bash.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.