John
John

Reputation: 31

Bash - not enough arguments

I have never used bash before but I am trying to understand this piece of code. The script is supposed to display all log in names, full names and their user-ids. However, whenever I run I can not get past the first if statement and if I delete the statement, it does not work.

#!/bin/bash 
if [ $# -lt 1 ]; 
   then 
   printf "Not enough arguments - %d\n" $# 
   exit 0 
   fi 

typeset user="" 
typeset name="" 
typeset passwdEntry="" 
while [ $# -ge 1 ]; 
   do 
   user=$1 
   shift 
   name="" 
   passwdEntry=`grep -e ^$user /etc/passwd 2>/dev/null` 
   if [ $? -eq 0 ]; then 
   name=`echo $passwdEntry|awk -F ':' '{print $5}'` 
fi 
echo "$user $name" 
done

Upvotes: 2

Views: 8149

Answers (1)

ruakh
ruakh

Reputation: 183201

$# means "the number of arguments to the current Bash program", and $1 means "the first argument to the current Bash program".

So your problem is that you're not passing any arguments to the program; for example, instead of something like this:

./foo.sh

you'll need to write something like this:

./foo.sh USERNAME

As you are new to Bash, I highly recommend skimming and bookmarking the Bash Reference Manual, http://www.gnu.org/software/bash/manual/bashref.html. It's all on a single page, so you can use your browser's "find in page" function (typically Ctrl+F) to search for things.

Upvotes: 4

Related Questions