File Permissions with Shell Scripting

Shell Scripting @ Freshers.in

Introduction to File Permissions and Shell Scripting

Managing file permissions is a fundamental aspect of Unix-based operating systems, allowing users to control access to files and directories. In this article, we’ll explore how to write a Shell script that takes a file name as an argument and changes its permissions. We’ll provide a step-by-step explanation of the script, along with practical examples and output.

Understanding File Permissions

File permissions in Unix-like systems are represented by a set of three octal digits: read (4), write (2), and execute (1), corresponding to the file owner, group, and others. These permissions determine who can read, write, or execute the file.

Writing the Permission Change Shell Script

Let’s create a Shell script named change_permissions.sh that takes a file name as an argument and changes its permissions based on user input.

#!/bin/bash

# Check if the correct number of arguments are provided Learning @ Freshers.in 
if [ "$#" -ne 2 ]; then
    echo "Usage: $0 <file_name> <permissions>"
    exit 1
fi
# Assign arguments to variables
file_name=$1
permissions=$2
# Change file permissions
chmod "$permissions" "$file_name"
echo "Permissions for $file_name changed to $permissions"
We use the chmod command to change file permissions.

The script takes two arguments: the file name and the desired permissions.

The "$permissions" variable holds the new permissions provided as an argument.

The "$file_name" variable holds the name of the file provided as an argument.

Example Usage and Output

Let’s assume we have a file named example.txt and we want to change its permissions to read and write for the owner and read-only for the group and others.

$ ./change_permissions.sh example.txt 644
Author: user