MacOS – How to scan a folder for subfolders, and copy a file to every output

bashmacmacos

I'm having a little bit of an issue here.
Here's the situation: We will be deploying a new application soon, and the server configuration resides in a simple XML file, located somewhere deep in the ~/library/Preferences. I want to create a bash/shell script that will basically copy the XML file at the right place, but for every user folder that exists.

I was able to use the below script for Windows, but I'm wondering if there is something similar for Apple.

Here's the Windows script:

$sourceLocation = "C:\Users\suptech\Downloads\TEMP"

$targetLocation = "C:\Users"

$result = @()

$result += get-ChildItem $targetLocation | Where-Object {$_.PSIsContainer}  
$result | foreach-Object { copy-item $sourceLocation -Destination "C:\Users\$_\AppData\Roaming\TEST” -Recurse -Force}

Could someone help me ?

Thanks in advance! 🙂

Best Answer

Well, here's something that you can work with. It isn't tested in a real world environment and is offered AS IS- without any warranty.

# This script must run as root
if [ "$(id -u)" != "0" ]
then
    echo "This script must be run as root"
    exit 1
fi

source=/path/to/file
destination=Library/path/to/destination/directory

for u in /Users/*
do
    on=${u##*/}

    # If not a directory- do not process
    [ ! -d "$u" ] && continue

    # Check that the directory has a valid user name or do not process
    id "$on" >/dev/null 2>&1 || continue

    # Get the user's primary group id
    gn=$(id -gn "$on")

    # bug fix found by Alex Pilon
    # make destination directory if it doesn't exist
    install -o "$on" -g "$gn" -d "${u}/${destination}"

    install -b -o "$on" -g "$gn" -m 644 "$source" "${u}/${destination}"
done

Another solution based on bmike's suggestion

# This script must run as root
if [ "$(id -u)" = "0" ]
then
    : running as root
else
    echo "This script must be run as root"
    exit 1
fi

source=/path/to/file
destination=Library/path/to/destination/directory 

dscl . -list /Users NFSHomeDirectory |
awk 'BEGIN { OFS=":" } / \/Users/ { print $1, $2 }' |
while IFS=: read u hdir
do
    # Get the user's primary group id
    gn=$(id -gn "$u")

    install -o "$u" -g "$gn" -d "${hdir}/${destination}"    

    install -b -o "$u" -g "$gn" -m 644 "$source" "${hdir}/${destination}"
done