Skip to content

Instantly share code, notes, and snippets.

@craSH
Created January 20, 2010 20:02
Show Gist options
  • Save craSH/282185 to your computer and use it in GitHub Desktop.
Save craSH/282185 to your computer and use it in GitHub Desktop.
Simple script that will set the ownership of a file to that of the directory in which it resides.
#!/bin/bash
#
# Simple script that will set the ownership of a file to that
# of the directory in which it resides. Useful for example,
# after copying a file from /home/user_alpha/ to /home/user_bravo/
# and you want it to have user_bravo's uid/gid so they can
# access it.
#
# This script is pretty naive, it would most certainly fail
# if a filename had a forward slash in it somehow.
#
# 2010 Ian Gallagher <crash@neg9.org>
#
# The file name being chown'd
target=$1
# Remove escaping backslashes, as we will always quote
target=$(echo "$target" | sed -e 's/\\//g')
# If there's no leading slash, prepend the current dir to it
echo "$target" | grep -q '^/' || target="$(pwd)/${target}"
# The directory that file resides in
parentdir=$(echo "$target" | grep -o '^.*/')
# Get the UID/GID of the parent directory
parentdir_uid=$(stat --format='%u' "$parentdir")
parentdir_gid=$(stat --format='%g' "$parentdir")
# Chown the target file to the uid/gid of the parent dir
chown -R ${parentdir_uid}:${parentdir_gid} "$target"
# Display the long listing of the file to the user
ls -lhd "$target"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment