Making a Script Executable with chmod

Su Suriya Ravichandran Updated 06 Dec 2026
9 min read ·Lesson 27 of 205

A new text file cannot be run as a program until you give it permission. In Linux, macOS and WSL, every file carries a set of permissions, and one of them, execute, decides whether the file may be started. The chmod command (short for change mode) changes these permissions. In this lesson you will learn how to read permissions, how to add and remove the execute permission, how the numeric modes such as 755 work, and why new files do not come with the execute permission.

Understanding the Concept

Every file has an owner, a group, and three kinds of permission. A permission answers one question: may this person do this thing to this file?

  • r (read): the contents may be read.
  • w (write): the contents may be changed.
  • x (execute): the file may be run as a program.

Permissions are given separately to three classes of people:

  • u: the user who owns the file.
  • g: the group that the file belongs to.
  • o: others, meaning everyone else.

The letter a means all three classes.

This design is a safety measure. A file you download or create is not allowed to run until a person deliberately grants the execute permission, so a harmful file cannot start by accident.

Reading Permissions

The ls -l command shows permissions in its first column:

ls -l report.sh
-rw-r--r-- 1 suriya suriya 42 Nov 20 10:00 report.sh

The first column has ten characters. The first character is the file type (- for a regular file, d for a directory). The next nine are three groups of three, for user, group and others:

-  rw-  r--  r--
|  |    |    |
|  |    |    +-- others: read only
|  |    +------- group: read only
|  +------------ user (owner): read and write
+--------------- file type: regular file

A dash in a position means that permission is not granted. A faster way to see only the permissions and the name is the stat command with a format string:

stat -c '%A %a %n' report.sh
-rw-r--r-- 644 report.sh

The %A part prints the letters, %a prints the same permissions as a number (explained below), and %n prints the file name. The -c option with a format string belongs to GNU stat; the stat on macOS uses different options.

Why a Script Does Not Run at First

Create a script and try to run it directly:

printf '#!/usr/bin/env bash\necho "report ready"\n' > report.sh
./report.sh
echo "status=$?"

Output:

bash: ./report.sh: Permission denied
status=126

The file has rw- for its owner, so there is no x. Bash refuses, and the exit status 126 means "found, but cannot be executed". Now add the permission:

chmod +x report.sh
stat -c '%A %a %n' report.sh
./report.sh

Output:

-rwxr-xr-x 755 report.sh
report ready

Three x characters appeared, and the script ran.

The chmod Syntax

chmod [options] mode file...

The mode can be written in two ways: symbolic (letters) or numeric (digits). Both change the same bits.

Symbolic Mode

A symbolic mode has three parts: who, an operator, and the permissions.

[ugoa][+-=][rwx]
  • who: u, g, o or a. If omitted, the change applies to all classes, adjusted by the umask (explained later).
  • operator: + adds the permission, - removes it, and = sets exactly these permissions and clears the others.
  • permissions: any combination of r, w and x.

Some examples, starting from a file with mode 755:

chmod u-x report.sh        # remove execute from the owner
stat -c '%A %a' report.sh
-rw-r-xr-x 655

Only the owner's x disappeared. Now several changes at once, separated by commas:

chmod a+x report.sh        # everyone may execute
chmod go-rwx report.sh     # group and others lose all permissions
stat -c '%A %a' report.sh
-rwx------ 700

The = operator sets a class exactly:

chmod u=rwx,g=rx,o= report.sh
stat -c '%A %a' report.sh
-rwxr-x--- 750

The part o= with nothing after it means "others get no permissions".

The most common command for scripts is plain chmod +x. When you leave out the "who", the change goes to all classes, except for bits that your umask removes. With the usual umask 022, the execute bit is not affected, so +x adds x for everyone, as the earlier output showed. If you want only the owner to be able to run the file, write chmod u+x instead.

Numeric Mode

Each permission has a value, and the values are added up to make one digit for each class:

PermissionValue
read (r)4
write (w)2
execute (x)1

For example, rwx is 4 + 2 + 1 = 7, r-x is 4 + 0 + 1 = 5, and r-- is 4. A mode has three digits, in the order user, group, others:

ModeLettersMeaning
755rwxr-xr-xOwner can do everything; everyone else can read and run. A typical script mode.
700rwx------Only the owner can read, change and run.
750rwxr-x---Owner full; group can read and run; others have nothing.
644rw-r--r--Owner can read and change; everyone can read. A typical data file.
600rw-------Only the owner can read and change.

Setting a mode in numeric form replaces all nine bits in one step:

chmod 755 report.sh
stat -c '%A %a' report.sh
chmod 644 report.sh
stat -c '%A %a' report.sh
-rwxr-xr-x 755
-rw-r--r-- 644

Use the numeric form when you know the exact result you want, and the symbolic form when you want to change only one thing without disturbing the rest.

Why New Files Are Not Executable: umask

A new file is not created with execute permission. Programs ask the system to create files with mode 666 (read and write for everyone), and the system then removes the bits listed in the umask. You can view it:

umask
0022

The value 022 removes write permission from the group and others, so a new file ends up as 644. The mask never adds execute permission to a new file, which is why every script starts without it.

A stricter umask produces more private files. The brackets below run the commands in a subshell, so the umask is only changed there:

( umask 077; touch private.txt; stat -c '%A %n' private.txt )
-rw------- private.txt

Changing Several Files and Directories

Give chmod more than one file, and it changes them all:

touch a.sh b.sh
chmod +x a.sh b.sh
stat -c '%A %n' a.sh b.sh
-rwxr-xr-x a.sh
-rwxr-xr-x b.sh

With a wildcard, chmod u+x *.sh makes every script in the current directory executable for its owner. The wildcard is expanded by Bash before chmod runs.

The -R option works recursively, applying the change to a directory and everything inside it:

mkdir -p tools
touch tools/c.sh
chmod -R u+x tools
stat -c '%A %n' tools tools/c.sh
drwxr-xr-x tools
-rwxr--r-- tools/c.sh

Be careful with -R and a plain x: it also makes ordinary data files executable. The capital X solves this. It sets execute permission only on directories, and on files that already have execute permission for someone:

mkdir -p proj/sub
touch proj/f.txt proj/sub/g.txt
chmod -R u=rwX,go=rX proj
stat -c '%A %n' proj proj/sub proj/f.txt proj/sub/g.txt
drwxr-xr-x proj
drwxr-xr-x proj/sub
-rw-r--r-- proj/f.txt
-rw-r--r-- proj/sub/g.txt

The directories gained x, and the text files did not. For a directory, the x permission means "may enter it", so directories nearly always need it.

To see what chmod did, use -v (report every file) or -c (report only the files that changed):

chmod -c 600 a.sh
chmod -c 700 a.sh
mode of 'a.sh' changed from 0755 (rwxr-xr-x) to 0600 (rw-------)
mode of 'a.sh' changed from 0600 (rw-------) to 0700 (rwx------)

Read Permission Is Needed Too

For a script, the execute permission is not enough on its own. The interpreter has to read the file, so the read permission is also required. The following test was run as an ordinary user (not the administrator, who bypasses permission checks):

chmod 311 r.sh     # owner: -wx   group: --x   others: --x
./r.sh
bash: ./r.sh: Permission denied

Without r, even the owner cannot run the script. The same mode with the read bit restored runs normally:

chmod 755 r.sh
./r.sh
report ready

Running bash script.sh is different: it needs only the read permission, because bash itself is the program being executed, and the script is just data. A file with mode 644 can be run with bash script.sh even though ./script.sh is denied. The next lesson explains these ways of running a script in detail.

Checking and Testing Permissions

To check from inside a script whether a file may be executed, use the -x test:

[ -x report.sh ] && echo "report.sh executable"
report.sh executable

The -x test is true if the current user may execute the file. Later lessons on conditions cover this and the other file tests (-r, -w, -f, -d) in detail.

Error Messages

chmod reports problems clearly. Both of these return the exit status 1.

A file that does not exist:

chmod +x nosuch.sh
chmod: cannot access 'nosuch.sh': No such file or directory

A mode that is not valid:

chmod 999 a.sh
chmod u+q a.sh
chmod: invalid mode: '999'
Try 'chmod --help' for more information.
chmod: invalid mode: 'u+q'
Try 'chmod --help' for more information.

In numeric mode, each digit must be from 0 to 7, and in symbolic mode only r, w, x (and a few special letters) are allowed after the operator.

Only the owner of a file, or the administrator, may change its mode. If you try to change a file that belongs to someone else, chmod replies with Operation not permitted.

Practical Applications

A personal tools folder. If you keep scripts in ~/bin, make them runnable by you alone:

chmod 700 ~/bin/*.sh

A script shared with a team. If your group should run a deployment script but nobody else, grant the group read and execute, and no one else anything:

chmod 750 deploy.sh

A script that must not be edited by accident. Remove the write permission, and the file protects itself from careless changes:

chmod 555 backup.sh

Permissions you should avoid granting. Mode 777 gives everyone, including other users on the machine, permission to change the file. A script that others can edit is a script that others can use to run their own commands as you. Choose 755 or 750 for scripts and 700 for anything private.

On the Windows side of WSL (paths such as /mnt/c/...), the permission bits are stored differently, and chmod may appear to have no effect unless the drive is mounted with the metadata option. Keep scripts in the Linux home directory when you work in WSL.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Making a Script Executable with chmod and get answers drawn from it.

Signed-in readers only.