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
?
Asked
Active
Viewed 51 times
0

Cyrus
- 84,225
- 14
- 89
- 153

Friendly Fella
- 75
- 1
- 2
- 10
-
1There are ways to 2 read a line: using character by character, or using [`readline`](https://en.wikipedia.org/wiki/GNU_Readline). Most modern `read` implementations use the `readline` library, which internally takes care of interpreting left arrow as cursor movement and not literal`^[[D`. – anishsane Jul 16 '19 at 04:37
-
1Sorry, I was wrong. `read` uses `readline` only when it is passed the `-e` option; as answered by Amadan. – anishsane Jul 16 '19 at 04:46
-
@anishsane No problem, can you provide more info/documentation on the character by character method? – Friendly Fella Jul 16 '19 at 04:51
-
1For 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. – anishsane Jul 16 '19 at 04:54
1 Answers
3
read -e
will interpret arrows correctly. From man bash
:
-e
If the standard input is coming from a terminal,readline
(seeREADLINE
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)

Amadan
- 191,408
- 23
- 240
- 301
-
How can we check characters one by one to confirm that no `/` character is entered while using the `read` method? – Friendly Fella Jul 16 '19 at 04:50
-
3"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](https://stackoverflow.com/questions/229551/how-to-check-if-a-string-contains-a-substring-in-bash). – Amadan Jul 16 '19 at 04:51