File processing

bash-2.05$ vi file_read.sh
"file_read.sh" 9 lines, 97 characters
#!/bin/ksh

print "Enter the group name"
read gname

varA= grep "$gname::" group

print $varA

This is the scenario: I am trying to get a userid and groupname from user and trying to add the userid to the given group. Please advise how to do this in KSH

What OS are you on? If you are on linux you can:

useradd -G {group-name} username

If Solaris:

usermod -G $(groups username| sed -e 's/.*: *//' -e 's/  */,/g'),{group-name} username

If AIX:

chuser groups=$(groups username| sed -e 's/.*: *//;s/  */,/g'),{group-name} username
user="UserName"
group="GroupName"

awk -v u=$user -v g=$group -F: '{if ($1==g) $NF=$NF","u}1' OFS=: /etc/group 

bash-2.05$ cat file_read.sh
#!/bin/ksh

print "Enter the group name"
read GroupName
Print "Enter the user name"
read UserName

user="UserName"
group="GroupName"

awk -v u=$user -v g=$group -F: '{if ($1==g) $NF=$NF","u}1' OFS=: group

bash-2.05$ ./file_read.sh
Enter the group name
staff
./file_read.sh[6]: Print: not found
user
awk: syntax error near line 1
awk: bailing out near line 1

I am getting the following error.

in Solaris , use nawk or /usr/xpg4/bin/awk

print "Enter the group name"
read group
Print "Enter the user name"
read user

nawk -v u=$user -v g=$group -F: '{if ($1==g) $NF=$NF","u}1' OFS=: /etc/group

I don't see the file updated.

bash-2.05$ cat group | grep staff
staff::10:

Ok, the awk command will not update /etc/group directly.

if output is correct, redirect to a temp file, and change the name back to /etc/group.

why its adding like this. I need to make sure it does not add , in the first place. But i do need after first user added.
staff::10:,mano

if your sed support -i option, before run the command, backup /etc/group first.

sed -i "/^$group:/ s/$/$user,/" /etc/group

above awk can be updated:

nawk -v u=$user -v g=$group -F: '{if ($1==g) $NF=($NF=="")?u:$NF","u}1' OFS=: /etc/group

I still think you are wise to use the OS command designed for doing this job, it takes into account many other factors including shadow files and the like. By all means put your own front-end on it to prompt for (and validate) the parameters, but stick with the tool designed to get the job done right.

should i use sed after nwak command.

bash-2.05$ vi file_read.sh
"file_read.sh" 9 lines, 171 characters

#!/bin/ksh

print "Enter the group name"
read group
print "Enter the user name"
read user

nawk -v u=$user -v g=$group -F: '{if ($1==g) $NF=$NF","u}1' OFS=: group > mano

You should at a minimum validate the entered user and group exist before doing anything.