实例一:向某个组批量复制文件
文件:copyfile:脚本文件
hello: 要复制的文件
#! /bin/bash
# ./copyfile eda hello
Group=$1 # 组名
if [ ! -f $2 -a ! -f $(pwd)/$2 ]; then
echo "The File To Copy Not Exists..." # 文件是否存在
exit 1
fi
if [ ! -f "/$2" ]; then # 文件全名
FileName=$(pwd)/$2
else
FileName=$2
fi
File=`echo $FileName|awk 'BEGIN{FS="/"}{print $NF}'`# 文件名
echo "==> The Copy File is $FileName"
USERS=`cat /etc/group|\ # 获取组用户名列表
awk -v group=$Group 'BEGIN{FS=":"} $1==group {print $4}'|\
awk 'BEGIN{FS=","} {for(i=1;i<=NF;i++) print $i}'`
echo "==> The Group is $Group"
for user in $USERS
do
echo "Will Copy To $user ..."
userhome=`finger $user|awk '$1=="Directory:"{print $2}' #获取用户Home`
if [ -f $userhome/$File ]; then # 文件已存在的话则删除
echo "the file in $user is exist..."
rm -f $userhome/$File
echo "have removed the file "
fi
cp $FileName $userhome #复制文件
chown $user $userhome/$File # 更改所有者
chgrp $Group $userhome/$File # 更改所有组
done
echo "All Users in Group $Group is OK..."
运行:
./copyfile eda hello
实例二:删除某个组用户的文件
文件: rmfile:脚本文件
hello:要删除的文件
#! /bin/bash
# ./rmfile eda hello
Group=$1 # 组名
File=$2 # 文件名
USERS=`cat /etc/group|\ # 获取组用户
awk -v group=$Group 'BEGIN{FS=":"} $1==group {print $4}'|\
awk 'BEGIN{FS=","} {for(i=1;i<=NF;i++) print $i}'`
echo "==> The Group is $Group"
for user in $USERS
do
echo "Will Copy To $user ..."
userhome=`finger $user|awk '$1=="Directory:"{print $2}'`# 用户HOME
if [ -f $userhome/$File ]; then # 判断文件是否存在
rm -f $userhome/$File
echo "have removed the file "
fi
done
echo "All Users in Group $Group is OK..."
运行:
./rmfile eda hello