This is my first time posting here so any feedback is very welcome should I be doing something wrong! I'm very new to shell scripting and am trying to write a function that checks whether an item is in a list. In this case I'm checking whether a given argument correspond to an existing user on the system. I really want to avoid false positives by making sure the item is surrounded by spaces but that obviously excludes the first and last item in the list. I figured maybe I could add spaces to the start and end of the list but I can't figure out how to do this. Any tips or pointers are very welcome! My code so far comes from this post. It looks like this:
-->This is the list of existing users
users=$(getent passwd {1000..60000} | awk -F ':' '{print $1}')
-->Function to check whether the given command line argument is in existing users
contains(){
[[ $1 =~ (^|[[:space:]])"$2"($|[[:space:]]) ]] && return 0 || return 1
}
Where $1 is the list of users obtained with getent from passwd file (see above) and $2 is the given (command line) argument I'm trying to validate.
Just as information: for testing purposes I've been trying out the contains function with a list (1 2 3 4). It works if I check this against 2 and 3, but not for 1 and 4.
getent passwd "$username" >/dev/null
instead. Not posting that as an answer, as a proper answer should probably reference the code that you are using. You also seem to be missing]]
before&&
, and you should mention what the values$1
and$2
looks like. – Kusalananda♦ Jun 11 '19 at 21:01