Open In App

Bash Script – File Permissions

Last Updated : 31 Jul, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will discuss file permission in Bash Script

To understand the scenario let’s take an example. Let’s consider there is a system admin A for company XYZ he designs a script that is to be executed by a user at 8:00 PM daily to send a report. He designs the script but forgets to give permission to the user to execute the script. Whenever a user tries to execute a script, he gets the error You are not authorized to take this action so why did this happen?

In the above case, we see that the system admin created a script but he did not give permission to the user as he was unable to execute it so to go into depth about this let’s explain how can we set file permission and how to check them.

Solution:  Now for the above example the system admin only has to give or set the user file permission to execute so that he can execute that file

So, what are the file permissions? 

File permissions can be described as who, what, and which activities can be done to a file or directory.

  • who refers to users, groups, or others
  • what means to add, delete and set
  • which means read, write, and execute

Basic list views of file and their permissions

The command we use is ls -l to show us the list of files/directory in the current folder we are present. This screenshot is a common example to show permission (using normal centos7 )

List of all files and directories with their permissions

From the above screenshot, let’s take a file let’s say luser_t04.sh, and see its file permissions

-rwx rwx rwx    1 root     root             0 Feb 27 17:35 luser_t04.sh

  1     2      3

(r = read , w= write ,  x = execute)

  • 1 represents the permission of the user, they have all the 3 permission to read, write and execute the file
  • 2 represents the group to which the file is associated  it also has all the permissions
  • 3 represent others  which also contains all the 3 permissions

Manage file permissions

To manage file permissions, we have a command called chmod which we can use to change the permission of files and directories.

Method to use chmod command

There are 2 methods to use the command 

  • Symbolic method
  • Numeric method

Symbolic Method

Syntax:

chmod whowhatwhich File|directory 

  • who is u(user) , g(group) , o(other)
  • what is to  +(add) ,-(remove) ,+(set)
  • which  is r (read), w(write), x(execute)

Let’s see an example: –

Suppose you want to remove read and write permission of group and others from the file 

chmod go-rw  <FILE>    (can be any file name)

Example:

chmod go-rw  luser_t04.sh. The new permission will be like this  

-rwx–x–x    1 root     root             0 Feb 22 02:28 luser_t04.sh

changing permission using Symbolic method

Numeric method 

Syntax:

chmod  ###  file|directory 

#: represents each digit the permission for user, group and others. 

4 =read   2=write  1 = execute 

Let’s see the example from above:

Example to understand the numeric method 

 -rwx–x–x    1 root     root             0 Feb 22 02:38 luser_t04.sh

  • user permission has been represented by rwx  (4+2+1=7)
  • group permission has been described as  –x (0+0+1 =1)
  • other permission has been described as –x ( 0+0+1=1)

Let us take another example of a file  

File with permission of 640  what it means in numeric method  

-rw- r– —    1 root     root             0 Feb 22 02:36 file1.txt

  • user have read(4) and write(2)  permission represented by rw- (4+2+0=6)
  • the group has read(4)  permission represented by r– (4+0+0=4)
  • other have no permission(0) ,represented  by — (0+0+0=0)

Example of file with chmod 640 

In this example to set file permission for a file (Example:  FILE ) 

We want the user to be able to read, write and execute files but we don’t want groups to write and execute the file and others to only be able to execute the file so what command and syntax we should use

Solution:

chmod  741  FILE1  (can be any file name)

The new permission set will be  rwx r– –x for FILE

-rwx r– –x    1 root     root             0 Feb 22 02:28 file.txt

Changing permission using numeric method

Script for File permission  

We can explain the file permission by creating a simple script to execute and change the permission of the file after understanding file permissions. 

Step-By-Step commands in script: 

Step 1. First, we create a file or check if an existing file is there as mentioned in the screenshot. If the file is not present then we execute the command

   touch <FILENAME>    (this will create a new file)

Step 2.  Our aim is to remove the write permission of others and groups as mentioned in the screenshot we will execute the command in the script 

chmod 744 <FILENAME> 

Step 3. Finally, to check if permission is changed or not, we will use

ls -l 

The Script

#!/bin/bash

# script to change permission of file

# File variable to store file.txt location
FILE="file.txt"

# to check the file we want to change
# exists or not
if [[ ! -e "${FILE}" ]]
then
echo "creating ${FILE} file"
touch file.txt
fi

# to remove write permission of other and group of file
chmod 744 "${FILE}"

#to check if the permission are removed
ls -l "${FILE}"

Now we will execute this script and check if it works 

./file_perm.sh

Output

Output of script

NOTE: In writing script and executing it is important to check permission always after creating script ls  -l command 



Similar Reads

Bash Script - Difference between Bash Script and Shell Script
In computer programming, a script is defined as a sequence of instructions that is executed by another program. A shell is a command-line interpreter of Linux which provides an interface between the user and the kernel system and executes a sequence of instructions called commands. A shell is capable of running a script. A script that is passed to
3 min read
Bash Scripting - Introduction to Bash and Bash Scripting
Bash is a command-line interpreter or Unix Shell and it is widely used in GNU/Linux Operating System.  It is written by Brian Jhan Fox. It is used as a default login shell for most Linux distributions. Scripting is used to automate the execution of the tasks so that humans do not need to perform them individually. Bash scripting is a great way to a
10 min read
Bash Script - Define Bash Variables and its types
Variables are an important aspect of any programming language. Without variables, you will not be able to store any required data. With the help of variables, data is stored at a particular memory address and then it can be accessed as well as modified when required. In other words, variables let you store, read, access, and manipulate data. Workin
12 min read
Bash Script - Working of Bash Variables
A Bash script is a plain text file. This file contains different commands for step-by-step execution. These commands can be written directly into the command line but from a reusability perceptive it is useful to store all of the inter-related commands for a specific task in a single file. We can use that file for executing the set of commands one
7 min read
Bash Scripting - Write Output of Bash Command into Log File
Let there are some situations in which you have to save your output in a file ( generally called log file). Output can be user details ( username, password, Gmail, etc. ), products record ( buying or selling any goods ), or simply any kind of data that you can store in a log file. Let see how to write the output of the bash command into a log file.
4 min read
Shell Script to List Files that have Read, Write and Execute Permissions
In this article, We will learn how to list all files in the current directory that have Red, Write and Execute permission. Suppose, we have the following files in our current directory : Here, We have a total of 8 files in our current directory. Out of 8, we have Read, Write and Execute permission on 6 files and 2 have only Read and Write permissio
3 min read
Bash Script - File system
On a partition or disc, a file system is a logical grouping of files. A partition serves as a storage space for data and, if needed, can take up the entire hard disc. One file system may house the /file system, while another may house the /home file system. Your hard drive may have a variety of partitions, each of which typically only contains one
7 min read
Write a Bash Script to Print a Particular Line From a File
One useful tool for automating operations in Unix-based systems is bash scripting. The need to print a certain line from a file is one such requirement. This post will walk you through writing a basic Bash script that accomplishes that. The fundamentals of utilizing conditional statements, showing the intended output, and reading user input will al
3 min read
Bash Scripting - Bash Read Password without Echoing back
Generally, you can see on the login page, whenever we type a password either it show dot (•) or asterisk (*) instead of a password. They do so because to protect our system or account. In such a case, the login page read the password and in place of the password, it will show a dot or asterisk. And in some cases, a dot or asterisk also may not appe
3 min read
Bash Scripting - How to Run Bash Scripting in Terminal
In this article, we are going to see how to run bash script in terminal. For example, we create a bash file set of instructions or commands ( known as bash script ), and through command, we can run this file in terminal. Let see how to run bash script in terminal. Example 1 : In this example we print or echo some text on screen with the help of a t
2 min read
Difference Between #!/usr/bin/bash and #!/usr/bin/env bash
In this article, we are going to see that what is the difference between #!/usr/bin/bash and #!/usr/bin/env bash What is #!? This is called the shebang character sequence consisting of the character's number sign and an exclamation mark at the beginning of the script. It is also called sharp-exclamation, sha-bang, hashbang, pound-bang, or hash-pili
2 min read
Bash Scripting - Working of Bash Scripting
Bash Scripting is a crucial component of Linux's process automation. You can write a series of commands in a file and then execute them using scripting. A Bash script is a plain text file with a set of commands inside of it. These commands are a combination of ones we typically type on the command line ourselves (like ls or cp, for instance) and ot
6 min read
Bash Scripting - Difference between Zsh and Bash
A shell is an environment in which various commands can be executed, it provides an interface between the user and the UNIX system. Basically, a shell is a command-line interpreter which interprets the commands given by the user, it can also read the combination of such commands which is known as a shell script. The shell provides us with an enviro
2 min read
Bash Scripting - Bash Echo Command
In this article, we are going to see the echo command. The Echo command is a built-in command feature for Unix / Linux which is generally used to display the text or message on the screen. Syntax : $ echo [option][text]For Example : $ echo Geeks For GeeksOutput : Geeks For Geeks There are generally three options:-n: It does not print the trailing n
2 min read
Advance File Permissions in Linux
The Linux file permissions are not limited to "rwx" bits, there are 3 special permissions apart from these "rwx" permissions which are SUID,SGID,The Sticky Bit. This article is about the 3 special file permissions and how to set and remove those permission bits. Set-user-ID (SUID) In Linux by default when a user executes a file, The file gets execu
4 min read
SetUID, SetGID, and Sticky Bits in Linux File Permissions
As explained in the article Permissions in Linux, Linux uses a combination of bits to store the permissions of a file. We can change the permissions using the chmod command, which essentially changes the 'r', 'w' and 'x' characters associated with the file. Further, the ownership of files also depends on the uid (user ID) and the gid (group ID) of
6 min read
Bash shell script to find sum of digits
Given a number Num, find the sum of digits of the number.Examples: Input : 444 Output : sum of digits of 444 is : 12 Input : 34 Output : sum of digits of 34 is : 7 Approach: 1. Divide the number into single digits 2. Find the sum of digits . C/C++ Code # !/bin/bash # Program to find sum # of digits # Static input of the # number Num=123 g=$Num # st
1 min read
Bash Script to get Low Battery Alert in Linux
We are going to write a bash script that will speak "Battery Low" when the battery's charging percentage will go below some specified threshold value. Before starting this, first, we need to understand some basic commands and terminology which are described below:Some Bash Commands: acpi: This command returns the percentage of battery charged, whet
3 min read
Bash shell script to find out the largest value from given command line arguments
Write a shell script to find out the largest value from the given number of command-line arguments. Example: Special variables in bash: $@- All arguments. $#- Number of arguments. $0- Filename. $1, $2, $3, $4 ... - Specific arguments. Approach If the number of arguments is 0, end the program. If not zero, then Initialize a variable maxEle with firs
1 min read
How to Code Your Own Port Scanner Using BASH Script and netcat Tool in Linux?
The first step of penetration testing is reconnaissance (information gathering) which involves scanning for open ports in the machine. There are various tools available on the internet to perform port scanning but, the ability to make your own port scanner is just felt amazing. So here are the steps to follow in order to achieve the same. To make t
3 min read
How To Pass and Parse Linux Bash Script Arguments and Parameters
Parsing and Passing of Arguments into bash scripts/ shell scripts is quite similar to the way in which we pass arguments to the functions inside Bash scripts. We'll see the actual process of passing on the arguments to a script and also look at the way to access those arguments inside the script. Passing arguments before running We can pass paramet
7 min read
Bash shell script to find if a number is perfect or not
In this article, we will discuss how to write a bash script to find if a number is perfect or not. A perfect number is defined as, a positive number that is equal to the sum of its proper divisors. Smallest no is 6 ex= 1,2,3 are divisor of 6 and 1+2+3=6 Method 1: Using While LoopRead the input using the read command.Then run while loop with conditi
3 min read
Send mails using a Bash Script
Sending email via the command line can be quite a great feature to have especially on Linux which will allow some users to avoid using the GUI and installing all of the dependencies. We will look into the following article on how to write a BASH (shell) script that can send a custom email to any other email using the SMTP server. Creating Google Ap
9 min read
Pentmenu - Simple Bash Script for Recon and DOS Attacks
DOS attacks are full-filling the server resources and making the server act slow or sometimes crash the server due to the fulfillment of resources. This can be done through various automated tools by sending thousands of requests at the same time. Pentmenu is an automated tool that is inspired by the PentBox designed to performs various network fun
3 min read
How to Find Length of String in Bash Script?
In this article, we are going to see how to get string length in Bash scripting. Here are a few ways from which we can get the length of the string in BASH: Using the # operatorUsing while loopUsing expr commandUsing awk commandUsing wc command Using these mentioned tools and commands, we will be able to get the length of a string variable in the B
5 min read
Bash Script - Write Hello World Program
In this article, we are going to see how to write "hello world" program in Bash script. The bash script is a text file that contains a set of instructions ( i.e. codes or commands ) that can be executed in the terminal. In any programming language, the first program that we learn to write is " Hello World ". Stepwise ImplementationStep 1: Create an
2 min read
Yotter - Bash Script that performs Recon
Yotter tool is an automated tool used in the phase of Web Information Gathering and Fingerprinting. Yotter tool can perform Recon like Finding the target IPs, Finding the target IP ranges, detecting the subdomains from various online sites also brute-force for subdomains, and performing Port scanning on the target domain. Yotter tool performs brute
2 min read
Bash Script - Arithmetic Operators
In this article, we will see arithmetic operators in bash script. Arithmetic operators is used to perform arithmetic operations. Bash script supports 11 arithmetic operators. All the operators with their uses is given below: OperatorNameUseExample+AdditionIt adds two operandsresult= a+b-SubtractionIt subtract second operand from first oneresult= a-
3 min read
Byp4Xx - Bash Script To Bypass "403 Forbidden" Messages
Byp4Xx is a free and open-source tool available on GitHub. It's a python script. You must have python language installed in your kali Linux operating system in order to use the tool. Byp4Xx is used to bypass 403 forbidden on any domain or on any IP address. Byp4Xx has many features which are given below:- Byp4Xx has the features of Multiple HTTP ve
1 min read
Bash Script - Command Substitution
In order to understand command substitution, let us first discuss substitution in shell scripts. Substitution is a functionality by following which we can instruct the shell to substitute the actual value of an expression. Example: In the program below we have firstly created variable str and assigned it with the value "GeeksforGeeks" and then subs
4 min read
Article Tags :
three90RightbarBannerImg