lostintranslation
lostintranslation

Reputation: 25

Display error if no arguments are typed in command line

I need to write a program that reads through the passwd file in Linux. The user enters the name of the program and the desired username, then the program prints out the corresponding userID and homeDir. If no username is supplied or more than one user is entered, the program displays an error message.

Good ex)
User types:
lookupUser.pl jdoe123
Result:
UID: 123456
HomeDir: /home/jdoe123

Bad ex)
User types:
lookupUser.pl
Result:
Enter one, and only one username.

Bad ex)
User types:
lookupUser.pl jdoes123 ssanta456
Result:
Enter one, and only one username.

At some point, I had it all working but I started cleaning up the code and now I get an error "Use of uninitialized value $user in scalar chomp at ./lookupUser.pl line 6." when I do not enter a username.

Any help is greatly appreciated.

#!/usr/bin/perl
use strict;
use warnings FATAL => 'all';

my $user = $ARGV[0];
chomp ($user);

if ($#ARGV == -1 || $#ARGV >= 1){
    print "Enter one, and only one username.\n";
}

elsif (getpwnam("$user")) {
    (my $name, my $passwd, my $uid, my $gid, my $quota, my $comment,
        my $gcos, my $dir, my $shell) = getpwnam $user;
    #print "Name = $name\n";
    #print "Password = $passwd\n";
    print "UID = $uid\n";
    #print "GID = $gid\n";
    #print "Quota = $quota\n";
    #print "Comment = $comment\n";
    #print "Gcos = $gcos\n";
    print "HOME DIR = $dir\n";
    #print "Shell = $shell\n";
}
else {
    print "Username $user does not exist.\n";
}

Upvotes: 2

Views: 85

Answers (1)

toolic
toolic

Reputation: 62227

Only if there is exactly 1 argument passed to the program, do the check of the user name.

use strict;
use warnings FATAL => 'all';

if (@ARGV == 1 ) {
    my $user = $ARGV[0];
    chomp ($user);
    if (getpwnam("$user")) {
        (my $name, my $passwd, my $uid, my $gid, my $quota, my $comment,
            my $gcos, my $dir, my $shell) = getpwnam $user;
        print "UID = $uid\n";
        print "HOME DIR = $dir\n";
    }
    else {
        print "Username $user does not exist.\n";
    }
}
else {
    print "Enter one, and only one username.\n";
}

Upvotes: 2

Related Questions