Skip to content

Instantly share code, notes, and snippets.

@vicradon
Created May 7, 2025 07:10
Show Gist options
  • Save vicradon/f916d392c3867216241759068841f33b to your computer and use it in GitHub Desktop.
Save vicradon/f916d392c3867216241759068841f33b to your computer and use it in GitHub Desktop.
Set permissions for a directory like /var/www or /etc/nginx
#!/bin/bash
set -e
print_usage() {
echo ""
echo "Usage: $0 /path/to/directory [group]"
echo ""
echo "Arguments:"
echo " /path/to/directory Target directory to apply permissions"
echo " group Optional group name (default: users)"
echo ""
echo "This script:"
echo " - Keeps the current owner (user)"
echo " - Changes the group to the one you specify (default: users)"
echo " - Sets directory permissions to 775 with g+s (so new files inherit group)"
echo " - Sets file permissions to 664"
echo ""
echo "Example:"
echo " $0 /etc/nginx"
echo " $0 /home/kalio/project devteam"
echo ""
}
# --- Argument Parsing ---
if [[ "$1" == "-h" || "$1" == "--help" ]]; then
print_usage
exit 0
fi
TARGET_DIR="$1"
GROUP="${2:-users}"
if [[ -z "$TARGET_DIR" ]]; then
echo "❌ Error: Target directory is required."
print_usage
exit 1
fi
if [[ ! -d "$TARGET_DIR" ]]; then
echo "❌ Error: '$TARGET_DIR' is not a valid directory."
exit 1
fi
if ! getent group "$GROUP" > /dev/null; then
echo "❌ Error: Group '$GROUP' does not exist. Create it with: sudo groupadd $GROUP"
exit 1
fi
OWNER=$(stat -c "%U" "$TARGET_DIR")
echo "πŸ”§ Applying permissions to: $TARGET_DIR"
echo "πŸ‘€ Owner will remain: $OWNER"
echo "πŸ‘₯ Group will be set to: $GROUP"
echo ""
# --- Apply Permissions ---
echo "β†’ Setting ownership recursively to $OWNER:$GROUP ..."
sudo chown -R "$OWNER:$GROUP" "$TARGET_DIR"
echo "β†’ Setting directory permissions to 775 and adding setgid bit ..."
sudo find "$TARGET_DIR" -type d -exec chmod 2775 {} \;
echo "β†’ Setting file permissions to 664 ..."
sudo find "$TARGET_DIR" -type f -exec chmod 664 {} \;
echo ""
echo "βœ… Done: Collaborative permissions applied successfully!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment