Reputation: 35
I need to be able to search a user file and determine whether an input from a user is in that file. This does not work
if [ $uname == awk '{print $1}' user_file ]; then echo "success"; fi
basically I am looking for a way to return true if the name is in my user_file. Any examples I find of using if/then deal with integers for comparison. Can you not compare strings in bash?
user_file contains
username1 password
username2 password2
I am trying to write a script that checks that user_info file and if the user has entered the correct username and password then it will perform some other action.
if [ username/password in user_info ]; then [ do some other action ]
(yes, this is an assignment for a class. The instructor isn't great so I'm stuck googling and trying to figure out a lot of things on my own. So I'm not trying to get exact answers to my scripting question, I just need to figure out how if/then loops work with strings.)
Upvotes: 1
Views: 1079
Reputation: 203219
if awk -v uname="$uname" '$1==uname{f=1; exit} END{exit !f}' user_file; then echo "success"; fi
Upvotes: 2
Reputation: 2815
uname
is "${u1}"
here, andpword
is "${p1}"
I intentionally put the only copy of it in the 2nd to last row to make sure it has to scan through the whole file -
unless you're talking about 9 GB
or larger file, I think one can save more time to scan it once it's all loaded instead of row by row and doing it piecemeal - 1.35GB
input confirmed either found or not within 1.2 secs
:::
% f='test_userpass2.txt' ;
( time ( pvE0 < "${f}" \
\
| mawk2 '
END { exit +RS^index($+RS,__) # this version won't match
# because i hyphenated them
}' RS='^$' __="${u1}-${p1}" FS='^$' \
)
echo "\n\n exit code : ${?}\n" ) | ecp
sleep 3;
( time ( pvE0 < "${f}" \
\
| mawk2 '
END { exit +RS^index($+RS,__)
}' RS='^$' __="${u1} ${p1}" FS='^$' ) ;
echo "\n\n exit code : ${?}\n" ) | ecp;
in0: 1.35GiB 0:00:00 [3.46GiB/s] [3.46GiB/s][========>] 100%
( pvE 0.1 in0 < "${f}" | mawk2 'END { exit +RS^index($+RS,__) }' RS='^$' ; )
0.54s user 0.64s system 101% cpu 1.160 total
exit code : 1
in0: 1.35GiB 0:00:00 [3.43GiB/s] [3.43GiB/s][=========>] 100%
( pvE 0.1 in0 < "${f}" | mawk2 'END { exit +RS^index($+RS,__) }' RS='^$' ; )
0.56s user 0.61s system 98% cpu 1.191 total
exit code : 0
Upvotes: 0