BudiBadu Logo
Samplebadu

Bash by Example: File Permissions

Bash 5.0+

Understanding Unix file permission model with read, write, and execute bits for owner, group, and others, along with practical methods for viewing and testing permissions programmatically in shell scripts.

Code

#!/bin/bash

touch script.sh
touch data.txt

# View permissions
ls -l script.sh

# Output format example:
# -rw-r--r-- 1 user group 0 Jan 1 12:00 script.sh
# | |  |  |
# | |  |  +-- Others (Read)
# | |  +----- Group (Read)
# | +-------- Owner (Read, Write)
# +---------- Type (File)

# Check permissions programmatically
if [ -x "script.sh" ]; then
    echo "Executable"
else
    echo "Not executable"
fi

if [ -w "data.txt" ]; then
    echo "Writable"
fi

rm script.sh data.txt

Explanation

The Unix permission system is fundamental to multi-user operating systems. Every file and directory has permissions defined for three distinct categories of users: the Owner (the user who created or owns the file), the Group (a collection of users who share access), and Others (everyone else on the system). Each category is assigned a combination of three permission types: Read (r), Write (w), and Execute (x).

When you run ls -l, the output format is a 10-character string. The first character indicates the file type (- for regular file, d for directory, l for symbolic link, b for block device, c for character device, p for named pipe, s for socket). The remaining nine characters are grouped into three sets of three, representing permissions for owner, group, and others. A dash (-) in any position means that particular permission is not granted.

Permissions have different meanings for files versus directories. For files: Read allows viewing contents, Write permits modification, and Execute allows running the file as a program or script. For directories: Read allows listing filenames within the directory, Write permits creating or deleting files inside it, and Execute (often called "search" permission) allows entering the directory with cd and accessing files within it. Without execute permission on a directory, even if you have read permission, you cannot access the files inside.

Code Breakdown

2
ls -l displays detailed file information including the 10-character permission string (e.g., -rw-r--r--), owner, group, size, and modification time.
13-17
The [ -x file ] test checks if the current user has execute permission on the file. Returns true (0) if executable, false (non-zero) otherwise.
19-21
Similarly, [ -w file ] tests for write permission. Useful for pre-flight checks before attempting file modifications.
4-10
The comment block shows how to interpret the permission string format, breaking down the positions for file type and the three permission triplets.