NewBashUser226 NewBashUser226 - 4 months ago 23
Bash Question

BASH grep script

I am trying to work on a bash script that checks for a username in the argument of the script and then outputs the relevant lines from the /etc/passwd and /etc/group files (not the /etc/shadow file). Currently, I am utilizing a if then else loop to check the contents of the /etc/* directory and output the relevant information. My intention was to output simple text line if a match user is not found in the two files, thus a null value. However, it is outputting information that is totally incorrect for what I am looking for.As a new user to BASH, and linux is general, I am sure there are some glaring issues right away. However, I am trying to learn.

Any help with the code of my script or a point in the right direction would be greatly appreciated. Thank you.

#! /bin/bash


USERLOOK='grep -h $USERID ~/etc/* | grep :x:'

grep $1 ~/etc/*
if [ -z $1 ]; then
echo "User not found."
else
echo "$USERLOOK"
fi
exit 0

Answer

Finds any lines in /etc/passwd or /etc/group that contain the inputted username:

#!/bin/bash

USERLOOK=$(grep -h "$1" /etc/passwd /etc/group)

if [ -z "$1" ] || [ -z "${USERLOOK}" ]; then
    echo "User not found."
else
    echo "$USERLOOK"
fi