12 comment

  1. This will also copy files to home directory of system users (not all of them have home directories).

    This will prevent that this happens.

    ID=$(id -u $u)
    if [ $ID -ge 1000 ] ; then
    if [ -d ${UHOME}/${u} ] ; then
    … do copy here….
    fi
    fi

  2. [email protected]:~$ id -u nobody
    65534

    I’m pretty sure you don’t want to copy something to the nonexistent nobody’s homedir. :-P

    Someone , could have in the system other accounts that cannot login (or don’t have a home dir etc)..One way to find the active users of a system is :

    $ cat /etc/shadow | grep -v ‘[*!]’

    Users who are inactive(have disabled accounts ) have a * or $ (these users cannot login) at the field where they should have the password hash.

  3. You also need to safely handle pre-existing files of the same name. You can use the –backup option with install or cp, but you probably want to log it and/or inform users in some way.

  4. The users home directory isn’t necessarily in the /home directory, you should read it from the ‘directory’ field in /etc/passwd – field 6
    UHOME=$(grep '^${u}' /etc/passwd | cut -d: -f6)

  5. hmm… errr…..

    if you chown $_dir/${FILE} then you are trying to chown a nonexistant file,
    as this expands to /home/user//nas05/.newconfig-file

    chown $(id -un $u):$(id -gn $u) “$_dir/${FILE}”

    Maybe if you created a new variable:
    FILENAME=”.newconfig-file”

    then you changed the chown line:
    chown $(id -un $u):$(id -gn $u) “$_dir/${FILENAME}”
    it would expand properly?

  6. What if I want to copy into a folder? (ie: ~Desktop/) or other and that folder does not exist.
    I know you can include a test to see if it exists or not, and create it if necessary.

  7. Hi,
    Thanks for this post, was helpful
    For more compatibility with others OS than Linux (Solaris, HP-UX…) i get the uid / gid using old fashionned way
    _uid=”$(getent passwd | grep ${u} | cut -d: -f3)”
    _gid=”$(getent passwd | grep ${u} | cut -d: -f4)”

    and i get the users with getent aswell as i am using an LDAP
    _USERS=”$(getent passwd | awk -F’:’ ‘{ if ( $3 >= 500 ) print $1 }’)”

  8. Some modified version for multiple files copy, it’s not perfect code but it fork

    #!/bin/bash
    UHOME="/home"
    # note wild card allowed
    _FILES="/tmp/.bashrc /tmp/.bashrc-user"
    _USERS="$(awk -F':' '{ if ( $3 >= 500 && $3 <=1000 ) print $1 }' /etc/passwd)" # get list of all users
    
    for u in $_USERS
    do
      for f in $_FILES
      do
         _dir="${UHOME}/${u}"
         if [ -d "$_dir" ]
         then
         
           /bin/cp -f "${f}" "$_dir"
           
    	file_name=`basename ${f}`
    	
           chown $(id -un $u):$(id -gn $u) "${_dir}/${file_name}"
         fi
      done
    done
    

Leave a Comment