Removing specific users with specific information in their line in bash/unix

Viewed 40

I'm trying to manipulate csv data to only delete users with specific header attributes by creating a script file and running it, then it will read data from a csv and delete the users with specific information in their line... but when I run this script, it gives errors and shows information such as all the commands to use but when I go through the list of commands it gives, it doesn't work.

mycsv.csv

username,first,last,gender,dob,countries,airports,shells,cuisines,operands,water,nfl
mb8239,maaran,batey,m,april 16 1993,japan,tpa,sh,spanish,multiplication,hint,49ers
INPUT=mycsv.csv 
OLDIFS=$IFS
IFS=','
while read username first last gender dob countries airports shells cuisines operands water nfl
do
    if [ $shells == "sh" ]
    then
        userdel -r
    fi
done < $INPUT
IFS=$OLDIFS

From what I understand, if im trying to remove the users using the shell 'sh' then i would do userdel -r no?

1 Answers

Finally had a chance to get to my ubuntu machine and sort the awk system() command syntax out. Try the following awk command:

awk -F',' '(NR>1) {if ($8 ~ /sh/) {out=system("sudo userdel -r " $1 ); print out}}' mycsv.csv

Output:

userdel: user 'mb8239' does not exist
6

The userdel: user 'mb8239' does not exist is the output generated by the attempted deletion of a user that does not exist on the host, so is appropriate output. The 6 is the exit code of the userdel command that is also expected per the man page for userdel when a user does not exist:

EXIT VALUES
       The userdel command exits with the following values:

       0
           success

       1
           can't update password file

       2
           invalid command syntax

       6
           specified user doesn't exist

       8
           user currently logged in

       10
           can't update group file

       12
           can't remove home directory

If you do not care about the output from the userdel command then you can utilize the following to redirect the output to /dev/null:

awk -F',' '(NR>1) {if ($8 ~ /sh/) {system("sudo userdel -r " $1 " > /dev/null 2>&1")}}' mycsv.csv
Related