0

How do I format the 2 conditions below into one while loop which should ensure that data enter contains at least one alphabetical character and doesn't already exist in the directory /dev/null.

1

#name = "test123"
read -p "Enter you name: " name
until [[ "$name" =~ [A-Za-z] ]]; do
    read -p "Please enter a valid name: " name
done

2

while id -u $name 2>/dev/null>1 ; do # Checks if username already exists
read -p "Please enter valid input: "

I know there are different ways toformat the 2 arguments in the while loop as it depends on the 2 arguments however i am not sure.

I've found this source below which i could proceed to trial an error however I want to know why I choosing to format the condition in such a way.

Bash scripting, multiple conditions in while loop

Community
  • 1
  • 1
pythontamer
  • 109
  • 1
  • 10

1 Answers1

2

You can use your loop like this:

while read -r -p "Please enter valid input: " name; do
   [[ $name == *[a-zA-Z]* ]] && { id -u "$name" >/dev/null 2>&1 || break; }
done

echo "Got a good name: $name"
  • read is used in a while loop which will keel looping until a break is executed inside the loop.
  • $name == *[a-zA-Z]* will check for presence of an alphabet in input name. * is used for globbing on either side.
  • id -u command will return 0 if entered name is found in user database and break gets executed when id command fails (username is unique).
  • >/dev/null 2>&1 is used to suppress stdout/stderr from id command since we only care about return status of id.
anubhava
  • 761,203
  • 64
  • 569
  • 643