kamil_debski
kamil_debski

Reputation: 121

Prevent read from special character input

How can I prevent or check for invalid input from read?

As you can see I'm asking user for name of a feature directory but it still reads characters that can't be put in directory name.

read -p 'Enter directory name: ' create_dir

Upvotes: 0

Views: 431

Answers (1)

Socowi
Socowi

Reputation: 27205

In Linux, The only characters that cannot be part of a directory name are / and the null byte \0. The null byte cannot be stored inside a bash variable. So all you have to check for is the / and the empty name.

The sane way to handle invalid input would be

while
  read -rp 'Enter directory name: ' create_dir &&
  [[ -z "$create_dir" || "$create_dir" == */* ]]
do
  echo "Empty names or names containing '/' are forbidden."
done
declare -p create_dir

However, it seems you want to "disable" the / key and also disable enter unless the user wrote something valid. With some tricks, this can be done too. But some users may get freaked out by this because you never explained anything to them.

printf 'Enter directory name: '
create_dir=
while 
  read -rsN1 char &&
  [[ -z "$create_dir" || "$char" != $'\n' ]]
do
  [[ "$char" = / || "$char" = $'\n' ]] && continue
  create_dir+=$char     
  printf %s "%char"
done
echo
declare -p create_dir

As I said, I wouldn't recommend this. With above approach the user also loses the ability to correct their input using backspace.

Upvotes: 4

Related Questions