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.
--- 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.
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