-1

I need to write a script that prompts the user to enter a username and then if that username exists, lists all of the user's information from the password file and a list of all commands they are currently running. So far I have this:

#!/bin/bash

echo "Please enter username"
read username

if [ "$username" = cat /etc/passwd | cut -d: -f1 ]
then 
    //list all user info from passwd file
    id $username

    //list all commands they are running
    i dont know how to code this
fi


If you guys can help me fill in or change anything that will be great, thanks!

Scooby
  • 1
  • And for checking if the user exists: https://unix.stackexchange.com/a/272639/70524 – muru Nov 06 '19 at 02:53
  • @muru so is my if conditional right? – Scooby Nov 06 '19 at 03:08
  • 1
    @Scooby Even if your cat command was used with a command substitution like "$(cat … | cut …)", you would compare $username against the list of all usernames and this would very likely fail. Instead you could use grep with if grep -q "^${username}:" /etc/passwd; then … or test if the username exists with if id "$username" >/dev/null 2>&1; then … discarding the output of stdout and stderr. – Freddy Nov 06 '19 at 04:03
  • While you're learning (and even when you think you're not) I'd recommend https://shellcheck.net/ for reviewing your code. – Chris Davies Nov 06 '19 at 12:04

1 Answers1

0

Ok, it is pretty clear that you are being asked to work with grep and pgrep so you can do this (no loops, no conditionals, no cutting etc.)

#!/bin/bash
echo "USERNAME:"
read u

#echo "USERNAME CHOSEN: $u"

if ! grep -e "^$u" /etc/passwd >/dev/null; then
echo NO SUCH USER!!!
exit
fi

echo  -e "\v user:$u info from /etc/passwd: "

grep "^$u" /etc/passwd


echo -e "\v USERS COMMANDS" 
echo "PID       CMD"

pgrep -u $u -a |awk '{print $1,"\t",$2}'

NetIceCat
  • 2,294
  • 2
    Using if ! getent passwd "$u"; then echo no such user; exit 1; fi would shorten it and allow for use on systems running directory servers (except it would fail on macOS). It would also return a failure to the calling shell. You do the same grep twice, which is not needed (just don't redirect the first one to /dev/null), and you will match pauline if given the username paul. – Kusalananda Nov 06 '19 at 06:42