Home > OS >  Can I use awk in a conditional statement
Can I use awk in a conditional statement

Time:05-01

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.)

CodePudding user response:

if awk -v uname="$uname" '$1=="uname"{f=1; exit} END{exit !f}' user_file; then echo "success"; fi

CodePudding user response:

I suggest with bash:

#!/bin/bash

read -p "Enter username: " input

while read -r user pass; do
  if [[ "$user" == "$input" ]]; then
    echo "success"
    break  # exit from while loop
  fi
done < user_file
  • Related