Linux Bash Worklet to Copy Files to Users' Home Folder

Linux bash worklet to copy files to users' home folder

The following bash scripts will retrieve a list of existing, normal users on a Linux device and copy the specified file(s) to the users' home folders. These can be added to a worklet for use with Automox.

Single File:

  • Be sure to modify the UHOME variable with the path to the home folder, if different from "/home".
  • Modify the FILE variable with the full path to the file you want to copy, including the filename.
  • Modify the FILENAME variable with the filename of the file you want to copy.
#!/bin/bash

#Base home folder
UHOME="/home"

#Path to file to be copied
FILE="/tmp/test_file"
#Filename variable for chown command
FILENAME="test_file"

#Get a list of all normal users
_USERS="$(awk -F':' '{ if ( $3 >=500 ) print $1 }' /etc/passwd)"

#Iterate through user list and copy file
for u in $_USERS
do
	_dir="${UHOME}/${u}"
	#check that the directory exists
	if [ -d "$_dir" ]
	then
		/bin/cp "$FILE" "$_dir"
		#set permissions
		chown $(id -un $u):$(id -gn $u) "$_dir/${FILENAME}"
	fi
done

 

Multiple Files:

  • Be sure to modify the UHOME variable with the path to the home folder, if different from "/home".
  • Modify the _FILES variable with the full path to each file you want to copy, including the filenames.
#!/bin/bash

#Base home folder
UHOME="/home"

#Path to files to be copied
_FILES="/tmp/test_file /tmp/test_file2"

#Get a list of all normal users
_USERS="$(awk -F':' '{ if ( $3 >=500 ) print $1 }' /etc/passwd)"

#Iterate through user list and file list and copy files
for u in $_USERS
do
	for f in $_FILES
	do
		_dir="${UHOME}/${u}"
		#check that the directory exists
		if [ -d "$_dir" ]
		then
			/bin/cp -f "$f" "$_dir"
			file_name=`basename ${f}`
			#set permissions
			chown $(id -un $u):$(id -gn $u) "$_dir/${file_name}"
		fi
	done
done

 

Notes:

The following line checks the /etc/passwd file for users and filters them to accounts with a UID greater than or equal to 500, which prevents us from grabbing system accounts.

_USERS="$(awk -F':' '{ if ( $3 >=500 ) print $1 }' /etc/passwd)"
Was this article helpful?
0 out of 0 found this helpful