bashawketcpasswd

If conditional using Awk to search for exact Bash variable string


In writing a BASH script, I am attempting to confirm whether a username, passed as a cmd line parameter, exists on the system by referencing /etc/passwd. My syntax must be off because my code fails on existing and non-existing users.

username=${!#}
username_exists(){
exists=$(awk -F ':' '$1 == "$username" {print $1}' /etc/passwd | wc -l)

if [[ "$exists" == 0 ]];
then
    echo "Username does not exist"
    exit
fi
}

I suspect that my username variable isn't being read correctly. And/or the if comparison is wrong. Any help would be amazing!


Solution

  • Pass the username to awk as a variable and then let awk do all the processing.

    awk -F ':' -v username="$username" '$1 == "$username" { fnd=1 } END { if ( fnd != 1 ) { print "Username does not exist" } }' /etc/passwd