[linux] Write a .sh file so that all files under the folder have the ownership of the current user, and the user group, and assign file permissions

User permissions under linux system

user

In a Linux system, each user has a unique username and a user ID (UID), which are used to identify the user. Users can own their own files and directories, and can read, write and execute operations on these files and directories. At the same time, there is also a super user (also called root user) in the Linux system, which has the highest authority of the system and can perform arbitrary operations on the system.

user group

A user group is a collection of users with the same privileges. Each user can belong to one or more user groups. User groups can be used to control access to files and directories, and to restrict the execution of certain operations. User groups can also be used to assign tasks and manage users.

file ownership

Every file and directory has an owner and an owning group. The owner is the user who created the file or directory, and the all group is a user group that all users in the user group can access the file or directory. File ownership can be viewed through the ls -l command, where the first field represents the file type and permission information, the third field represents the owner, and the fourth field represents all groups.
In the Linux system, you can use the chown command to modify the owner and all groups of files and directories, and use the chmod command to modify the access permissions of files and directories. At the same time, you can also use the chgrp command to modify all groups of files and directories. These commands can be used to manage the access permissions of files and directories, and protect the security of files and directories.

bash script

mybash.sh

#!/bin/bash
# 获取输入的文件夹路径和权限参数
DIR_PATH=$1
PERMISSION=$2
# 如果没有输入权限参数,则默认为644
if [ -z "$PERMISSION" ]; then
    PERMISSION="640"
fi
# 获取当前用户和用户所在组
CURRENT_USER=$(whoami)
CURRENT_GROUP=$(id -gn)
# 修改文件夹下所有文件的所属用户和组
chown -R "$CURRENT_USER:$CURRENT_GROUP" "$DIR_PATH"
# 修改文件夹下所有文件的权限
find "$DIR_PATH" -type f -exec chmod "$PERMISSION" {
    
    } \;
echo "修改完成!"

Use scripts to modify all file permissions under the folder, belonging to the user:

Grant 777 permissions to all files under the myfile folder, and set the file ownership to the current user and user group:

bash mybash.sh ./myfile 777

Guess you like

Origin blog.csdn.net/hh1357102/article/details/131065649