Created
May 7, 2025 07:10
-
-
Save vicradon/f916d392c3867216241759068841f33b to your computer and use it in GitHub Desktop.
Set permissions for a directory like /var/www or /etc/nginx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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