How to write a UNIX script to send a mail to the respective individual users about their groups?

Hi Team,

I got a requirement to send a mail to the individual users of a unix server about their respective groups. can some one help me to provide the script as I am unable to write that.

I tried with below lines but I come out with errors.

cat /etc/passwd | awk -F':' '{ print $1}' | xargs -n1 groups

--- to get username and groups details
------------------------------------------------------------------
when i tried to send an mail to respective users it is throwing an error message as below:

syntax error near unexpected token `('
foreach user  ( `awk -F: '{ print $1 }' /etc/passwd ` ) 
    # Mail the file
    echo Mailing to $user
    mail -s "$subject" $user < $filename
   
    sleep 2
end

can some one can please help me with proper script.

Thanks in advance

Hi harshabag,
What operating system and shell are you using?

It appears that you might be using the syntax for commands in one shell while executing commands with a different shell.

Unix red hat OS, bash shell, can you please write some code as I am very new to this Unix.

Thanks in advance

Please become accustomed to provide decent context info of your problem.
It is always helpful to support a request with system info like OS and shell, related environment (variables, options), preferred tools, and adequate (representative) sample input and desired output data and the logics connecting the two, to avoid ambiguities and keep people from guessing.

On my linux system running above with bash , I receive

bash: syntax error near unexpected token `('

So - please post entire error messages to help people help you.

In (a recent) bash , your groups list could be achieved like

groups $(awk -F':' '{ print $1}' /etc/passwd)

or

groups $(cut -d: -f1 /etc/passwd)

, and your loop modified to

for user in $(cut -d: -f1 /etc/passwd); do mail -s "$subject" $user   < <(groups $user); done

might work.

A slightly different approach would reduce disk I/O activity by running groups only once:

groups $(cut -d: -f1 /etc/passwd) | while read line; do echo $line | mail -s"subject" ${line%%:*}; done

For something that would be more portable to a system where the groups utility only accepts one operand, the user database on your system is kept in the file /etc/passwd (which is not always true), and assuming that every user has a mail account with their login name as their mail address on that machine (which is not always true), you could also try:

cut -d: -f1 /etc/passwd | while read user
do	echo "Mailing to $user"
	groups "$user" | mail -s "$user's groups" "$user"
done

Does the same works if we want to email the users mail id ?

Hi Don,

Thanks for your valuable input's it worked well.

Regards,
Harsha.