-1

I want to create a Bash Script to check the existence of a user name in /etc/passwd. If it exists then add it to users.txt file.

I am not really good at UNIX programming, so I hope somebody can help me.

while(get to the end of /etc/passwd){

  name=$(cat /etc/passwd | cut -d: -f1);
  num1=$(cat /etc/passwd | cut -d: -f3);
  num2=$(cat /etc/passwd | cut -d: -f4);

  if(num1==num2)
   /*i compare argv[0] with $name */
   /* if true i=1 */

}

if(i==1)
  save following string "argv[0]=agrv[1]"
else
  "error message"
Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
DmitryK
  • 1,333
  • 1
  • 11
  • 18

3 Answers3

4
#!/bin/bash
read -p "Username: " username
egrep -q "^$username:" /etc/passwd && echo $username >> users.txt

Note: if you're only trying to test for the existence of a username, it might better just to use id:

if id -u $username >/dev/null 2>&1;
then
    echo $username >> users.txt
fi

The > /dev/null 2>&1 is only there to stop the output of id being printed (i.e. the uid of $username, if it exists, or an error message if the user doesn't).

Jay
  • 3,285
  • 1
  • 20
  • 19
0
#!/bin/bash   
read -p "Enter a username: " username
getUser=$(cat /etc/passwd | grep $username | cut -d":" -f1)
echo $getUser >> users.txt

Not really any need to have a loop as if it isnt there it won't add anything to the file.

Jon Lin
  • 142,182
  • 29
  • 220
  • 220
Alex
  • 1
  • 1
  • 1
    Useless use of cat: `grep $username /etc/passwd`. – chepner Jun 21 '12 at 15:14
  • In addition: you'll match the `$username` anywhere in the line. You need to ensure you've only `grep`'d a username. Also, if it doesn't match, you'll just output an empty line into `users.txt` – Jay Jun 21 '12 at 15:15
  • It's a good start anyway, there are some problems however, as mentioned – Onkelborg Jun 21 '12 at 16:30
0
#!/bin/bash

found=false

while IFS=: read -r name _ num1 num2 _
do
    if (( num1 == num2 ))
    then
        if [[ $name == $1 ]]
        then
            printf '%s\n' "$1=$2"
            found=true
        fi
    fi
done < /etc/passwd > users.txt

if ! found
then
    printf '%s\n' "error message" >&2
    if [[ -e users.txt && ! -s users.txt ]]
    then
        rm users.txt
    fi
fi
Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439