Bash:将文件拷贝到所有主目录



我必须复制(如果已经存在则覆盖)一个文件到同一组("students")的所有用户成员的主目录。

我找到了一个脚本,我试图适应我的上下文(我有LDAP用户而不是/etc/passwd,所以我使用getent passwd来获取用户名)。

下面是脚本(cp2studs .sh):
#!/bin/bash
# subdirectory of /home/uid
DIR=".eclipse/org.eclipse.platform_3.8_155965261/configuration"
# the file to copy
FILE="/home/admin/tmp/config.ini"
# location of home dirs
UHOME="/home" 
# GID of "students" group
USERS_GID=10004
# get list of users having same GID
_USERS="$(getent passwd | awk -F ':' '{if ( $4 == $USERS_GID ) print $1 }')"
for u in $_USERS
do
   _dir="${UHOME}/${u}/${DIR}"
   if [ -d "$_dir" ]
   then
     yes | /bin/cp -v "$FILE" "$_dir"
     chown $(id -un $u):students "$_dir/${FILE}"
   fi
done

当我尝试启动它时:

$ sudo cp2stud.sh

我什么也没得到。

我错在哪里?

Thanks in advance

_USERS="$(getent passwd | awk -v X="$USERS_GID" -F ':' '{if ( $4 == X ) print $1 }')"

试试这个方法:

...
export USERS_GID=10004
_USERS=$(getent passwd | awk -F ':' '{if ( $4 == ENVIRON["USERS_GID"] ) print $1 }')
...

你也可以这样做:

...
USERS_GID=10004
_USERS=$(getent passwd | awk -F ':' -v gid=$USERS_GID '{if ( $4 == gid ) print $1 }')
...

或只是:

...
_USERS=$(getent passwd | awk -F ':' -v gid=10004 '{if ( $4 == gid ) print $1 }')
...

下面的代码可以工作:

DIR=".eclipse/org.eclipse.platform_3.8_155965261/configuration"
FILE="/home/admin/tmp/config.ini"
UHOME="/home"
USERS_GID=10004
GRP_NAME=students
FILENAME=$(basename $FILE)

_USERS="$(getent passwd | awk -v X="$USERS_GID" -F ':' '{if ( $4 == X ) print $1 }')"
for u in $_USERS
do
  _dir="${UHOME}/${u}/${DIR}"
  if [ -d "$_dir" ]
  then
      yes | /bin/cp -v "$FILE" "$_dir"
      chown -v $(id -un $u):$GRP_NAME "${UHOME}/${u}/${DIR}${FILENAME}"
  fi
done

最新更新