Skip to content

Instantly share code, notes, and snippets.

@fredsiika
Last active June 11, 2019 21:49
Show Gist options
  • Save fredsiika/236dcd7f5dabcf43a474affc9895a62f to your computer and use it in GitHub Desktop.
Save fredsiika/236dcd7f5dabcf43a474affc9895a62f to your computer and use it in GitHub Desktop.
A simple shell script to locate username.
#!/bin/bash
# find-user.sh: A simple shell script to locate username.
# Author: Fred C. Siika
# GitHub: https://github.com/fredsiika
# Modify this script for your own purposes.
################################################################
# Goals of the script:
# How Do I Store Exit Status Of The Command In a Shell Variable?
# Assign $? to a shell variable:
# Example:
# ls -l /tmp
# status=$?
# echo "ls command exit stats - $status"
#
################################################################
clear
# Set the var for password file
PASSWD_FILE=/etc/passwd
# Get the user name
read -p "Enter a user name: " username
# Try to locate username in /etc/passwd
# Notice that standard output from grep command
# is ignored by sending it to /dev/null.
grep "^$username" $PASSWD_FILE > /dev/null
# Store exit status of grep.
# If found grep will return 0 exit status.
# If not found, grep will return a nonzero exit status.
status=$?
# Some human readible formatting
echo -e "==> User name entered: \033[1;35m$username\033[m"
sleep 1
echo -e "==> Searching file: \033[1;35m$PASSWD_FILE\033[m..."
sleep 1
echo -e "..."
sleep 1
# Adding progress bar
echo -ne '##### (33%)\r'
sleep 1
echo -ne '############# (66%)\r'
sleep 1
echo -ne '####################### (100%)\r'
# Check the status code of grep command.
# Prints output to Termainal (stdout).
if [ $status -eq 0 ]
then
echo -e "User: \033[1;35m$username\033[m found in \033[1;35m$PASSWORD_FILE\033[m file.\nExit Status: \033[1;32m$status\033[m";
else
echo -e "User: \033[1;35m$username\033[m not found in \033[1;35m$PASSWD_FILE\033[m file.\nExit Status: \033[1;31m$status\033[m"
fi
echo -ne '\n'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment