Question

I'm writing a bash script that creates directories and copy files under Mac OSX. Some of these directories and files need to be placed in folders owned by the system such as /Library/Audio/Plug-Ins, and so I run the script under sudo. Such script might look like:

copy-plugins.sh:

#!/usr/bin/env bash
mkdir -p /Library/Audio/Plug-Ins/My-Plugins
cp plugin-A.dylib /Library/Audio/Plug-Ins/My-Plugins
cp plugin-B.dylib /Library/Audio/Plug-Ins/My-Plugins

and called:

$ sudo ./copy-plugins.sh

However when running under sudo, all created directories and copied files are owned by root.

I would like to be able to run the script under sudo and have the files be owned by my user. I could call chown after each file/directory is created or copied

copy-plugins-cumbersome.sh:

#!/usr/bin/env bash
mkdir -p /Library/Audio/Plug-Ins/My-Plugins
chown 501:501 /Library/Audio/Plug-Ins/My-Plugins

cp plugin-A.dylib /Library/Audio/Plug-Ins/My-Plugins
chown 501:501 /Library/Audio/Plug-Ins/My-Plugins/plugin-A.dylib

cp plugin-B.dylib /Library/Audio/Plug-Ins/My-Plugins
chown 501:501  /Library/Audio/Plug-Ins/My-Plugins/plugin-B.dylib

but I'm hoping for a more general solution.

As far as I can tell there is no setuid for bash.

Was it helpful?

Solution

Use cp -p option to preserve file attributes.

Note this will preserve user, group permissions and the modification and access times of the files.

OTHER TIPS

As you need sudo to copy to the directories you are copying to in script, it means you need to be root to copy anything in those directories.

When you do sudo you are root for that particular command or script, so whatever will be created or executed will have root permissions. Till the time you specify.

The possible ways to come out of it without changing anything:

  1. The one you are using, and
  2. Other one to use -p or -a with cp
  3. rsync -go <source file> <destination file>

    -g for preserving group and -o for preserving ownership.

Note If you do a chown out of script, you will have to specifically do sudo chown since files you would be touching belong to root.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top