-2

Hi i am trying to do a bash script that checks if a username exists

echo "Enter desired username:"
read username

Search= true

while (Search= true)
do

getent passwd $username  > /dev/null

if [ $? -eq 0 ]; then
   echo "yes the user exists, try another username"
   read username
   Search= true
else
   Search= false 
   echo "No, the user does not exist"
fi
done  

If i type a username that exists it works as expected it runs the yes command ok

but if i type one that does not exists it enters an endless loop and keeps running "No, the user does not exist" and i have to close the terminal window

What have i done wrong here? Im only 8 weeks into a software development course.

If i type in a username that does not exist it endlessly prints

"No, the user does not exist"

kd305
  • 1
  • 3
    Pass your script to https://shellcheck.net – Gilles Quénot Nov 30 '22 at 18:31
  • `var= val` must be `var=val` (no space). Also `[[ $Search == true ]]` is the correct syntax. But instead I'd do: `while read -r username; do getent #etc... else break ... done` – dan Dec 11 '22 at 23:17

1 Answers1

0

You have basic but severe syntax errors.

echo "Enter desired username:"
# -r: don't mangle backslashes
read -r username

# can't have a space after =
Search=true

# use proper string comparison; use a dollar sign to reference the variable
while [[ $Search = true ]]
do
    # fix indentation
    # avoid $? antipattern
    # quote variable
    if getent passwd "$username" > /dev/null
    then
       echo "yes the user exists, try another username"
       read -r username
    else
       Search=false 
       echo "No, the user does not exist"
    fi
done  

The design with read for interactive prompting is rather user-hostile; you would probably prefer a simple command-line parameter, though then the script resolves to just

#!/bin/bash
getent passwd "$1"

This is superior in that it's callable from other scripts, and you get to use command-line facilities like history and autocompletion to recall earlier inputs.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • See also [Why is testing “$?” to see if a command succeeded or not, an anti-pattern?](https://stackoverflow.com/questions/36313216/why-is-testing-to-see-if-a-command-succeeded-or-not-an-anti-pattern) – tripleee Nov 30 '22 at 18:42
  • And [When to wrap quotes around a shell variable](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable) – tripleee Nov 30 '22 at 18:51