Reputation: 13
I have a list of names in a list (say name.txt) which has the set of name lists one by one.
name.txt
babu
praveen
kamal
sneha
This name will be passed as run time argument $1 in my bash script. Now I have to do a match to check if the inputted name is in my list or not.
If it's not there then I will print saying invalid name and exit. Can you help me with this?
I have tried this with
if [[ "$1" != "babu" || "$1" != "praveen" || "$1" != "kamal" ... ]]; then
exit
fi
but this doesn't look good professionally.
Is there any other simple and decent way to achieve this?
Upvotes: 0
Views: 173
Reputation: 74595
I guess you could use grep:
if ! grep -qFxf name.txt <<<"$1"; then
exit
fi
-q
is "quiet mode" - the exit status indicates a match-F
matches fixed strings, rather than regular expressions-x
is a full line match, so names that are substrings won't match-f
means that the list of patterns are contained within a fileThe string contained within the first argument is passed to grep using a here string. This is a bash feature, so if you're using another shell, you could go with something like if ! echo "$1" | grep -qFxf name.txt
instead (but the bash way is preferred as it saves invoking a subprocess).
If you want to ensure that any error output from grep is suppressed, you can add 2>/dev/null
to the command, as suggested in the comments. This prevents any messages sent to standard error from being displayed.
Upvotes: 2