This document explains a Bash script that checks and optionally changes file ownership in a specified directory.
The script performs the following tasks:
The script follows these steps:
find command to recursively search for all files in the specified directory.stat command.chown command to change the ownership of the incorrect files.Here's the complete Bash script:
#!/bin/bash
# Check if all required arguments are provided
if [ $# -ne 3 ]; then
echo "Usage: $0 <directory> <expected_user> <expected_group>"
exit 1
fi
directory="$1"
expected_user="$2"
expected_group="$3"
# Function to check and report ownership
check_ownership() {
local file="$1"
local current_owner=$(stat -c '%U' "$file")
local current_group=$(stat -c '%G' "$file")
if [ "$current_owner" != "$expected_user" ] || [ "$current_group" != "$expected_group" ]; then
echo "Incorrect ownership: $file"
echo " Current: $current_owner:$current_group"
echo " Expected: $expected_user:$expected_group"
return 1
fi
return 0
}
# Main script
echo "Checking file ownership in $directory"
incorrect_files=()
while IFS= read -r -d '' file; do
if ! check_ownership "$file"; then
incorrect_files+=("$file")
fi
done < <(find "$directory" -print0)
# Report and prompt for change
if [ ${#incorrect_files[@]} -eq 0 ]; then
echo "All files have correct ownership."
else
echo "Found ${#incorrect_files[@]} files with incorrect ownership."
echo "Do you want to change ownership for these files? (y/n)"
read -r answer
if [[ $answer =~ ^[Yy]$ ]]; then
for file in "${incorrect_files[@]}"; do
chown "$expected_user:$expected_group" "$file"
echo "Changed ownership: $file"
done
echo "Ownership change completed."
else
echo "No changes were made."
fi
fi
check_and_change_ownership.sh.chmod +x check_and_change_ownership.sh
./check_and_change_ownership.sh /path/to/directory expected_user expected_group
For example:./check_and_change_ownership.sh /home/user/documents john users