How to Make a Shell Script Executable in Linux
In the Linux operating system, newly created shell scripts are
treated as regular text files without execution privileges by default.
This guide provides a straightforward explanation of how Linux
permissions work for executable files, how to modify these permissions
using the chmod command, and how to successfully run your
script directly from the terminal.
Check Existing File Permissions
Before modifying permissions, check the current status of your script. Open your terminal, navigate to the directory containing your script, and run:
ls -l script.shThe output will display a permission string such as
-rw-r--r--. This string indicates:
- First character (
-): Represents a regular file. - Characters 2–4 (
rw-): Read and write permissions for the file owner. - Characters 5–7 (
r--): Read-only permissions for the group. - Characters 8–10 (
r--): Read-only permissions for others.
An executable script requires an x (execute) flag in
these permission slots.
Make the Script Executable Using chmod
The chmod (change mode) command is used to modify file
permissions. You can add execute permissions using symbolic mode or
numeric (octal) mode.
1. Symbolic Mode
To grant execute permissions to the file's owner only:
chmod u+x script.shTo grant execute permissions to all users (owner, group, and others):
chmod +x script.sh2. Numeric (Octal) Mode
Permissions can also be assigned using numbers where:
4= Read2= Write1= Execute
A standard permission set for an executable script is
755 (Owner: Read/Write/Execute 4+2+1=7; Group:
Read/Execute 4+1=5; Others: Read/Execute
4+1=5):
chmod 755 script.shIf you want only the file owner to have full access and restrict
everyone else entirely, use 700:
chmod 700 script.shVerify the Changes
Verify the permission update by running ls -l again:
ls -l script.shThe output should now show the x flag, looking similar
to:
-rwxr-xr-x 1 user user 120 May 10 12:00 script.sh
Ensure the Shebang Is Present
For the shell to interpret the script properly, make sure the first line of your script defines the interpreter. Open your script in a text editor and verify that the shebang is the very first line:
#!/bin/bashRun the Executable Script
Once execution permissions are granted and the shebang is in place, execute the script by specifying its path:
./script.shThe ./ tells the shell to look for the file in the
current working directory rather than searching the directories listed
in your system's PATH variable.