Bash script to copy permissions

2010-12-04
This is a bash script that I've used on Ubuntu in order to copy the permissions from a file or directory, onto the whole structure of another directory. I've found that this is something I like to do quite often and wanted some automation for this operation.

First of all I needed a few commands for my script. They were:

chown -R username:groupname dirname
chmod -R flags dirname

Where

Next step was to retrieve the current values for an existing file or directory that I know I wanted to copy the permissons from. For that, I can use the stat command with a format string:

stat -c%u:%g filename
stat -c%a filename

Where

Next, I needed to provide the output of the stat commands as input (or part of the input) to the chown and chmod commands. This is done with Bash using the following notation:

command $(command-with-output)

This led me to the following commands:

chown -R $(stat -c%u:%g source) destination
chmod -R $(stat -c%a source) destination

If you specify your own source and destination, these commands can be run from the Bash prompt. But I also wanted to put them inside a Bash script so I didn’t have to do all this typing. I also added some validation and came up with the following script:

#!/bin/bash
if [ -z $1 ] || ([ ! -d $1 ] && [ ! -f $1 ]); then
  echo "Not a file or directory as first argument"
  exit 0
fi
if [ -z $2 ] || [ ! -d $2 ]; then
  echo "Not a directory as second argument"
  exit 0
fi
chown -R $(stat -c%u:%g $1) $2
chmod -R $(stat -c%a $1) $2

Some things to note from the script:

This script has served me well. I hope you’ll find it useful too.

Leave a Reply

Twitter: @mikeplate