The UNIX and Linux Forums  


Go Back   The UNIX and Linux Forums > Top Forums > Shell Programming and Scripting
.
google unix.com




View Single Post in the UNIX and Linux Forums - Click on the Thread or Permalink to View Entire Thread -->
  #1 (permalink)  
Old 09-30-2008
ankimo ankimo is offline
Registered User
  
 

Join Date: Sep 2008
Posts: 23
for loop logic with multiple parameters

hi, unix wizards,

i have a question about the logic of my inner for loop below. first, what i am trying to do is to write a script called create_account that automatically creates mysql accounts. the user can provide a user_name or a group_id as an argument (and the script can take multiple arguments). user_name arguments should simply be appended to a user_file.

group ids should be compared to a file that contains a list of group_ids with multiple user_names per id. if the group id exists, then grab all the users and append to the user_file. if the group id does not exist, print "group id not valid".

of course, the first thing i have to do is validate the argument -- if its a number of a certain type, i assume its a group_id. else, it's a user_name. btw, "is_num" is a function to validate if the argument is a number (and hence, a group_id).


----------------------------------------------
get arg

  • if argument is a number
    • then validate group_id
    • if num is invalid group_id,
      • then print "group id not valid"
    • if num is valid group_id
      • then parse group_id_file and grab users from 4th field on
  • else
    • append to user_file
----------------------------------------------


my code works well when i have just one arguement and it doesn't matter if the arguement is valid group_id, an invalid group_id, or a user_name. but when i use multiple parameters, the problems with my code are:

  1. user_name arguments are getting passed through the inner for loop and shouldn't be because they don't pass the is_num function criteria
  2. commands with multiple parameters run all arguments multiple times
  • for example, if i say...
    Code:
    create_acct valid_num invalid_num

... i get a list with all the valid users times 2 i wonder if anyone has the time to point me in the right direction. thanks for your help.




Code:
for arg; do
  if is_num $arg; then

#----------------------------------------------

   for num; do
      a=$(grep "^c$num:" group_file)

      if [ -z "$a" ]; then
        print "Group ID " $num "is not in group file."
        continue
      fi

      f4=$(echo $a | cut -d: -f4)

      if [ -z "$f4" ]; then
        print "Group ID " $num "does not have any users."
      else
        print $f4 | tr ',' '\n' >> user_list
        continue
      fi
    done

#----------------------------------------------

  else
    echo $arg >> user_list
  fi
done