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.sh

The output will display a permission string such as -rw-r--r--. This string indicates:

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.sh

To grant execute permissions to all users (owner, group, and others):

chmod +x script.sh

2. Numeric (Octal) Mode

Permissions can also be assigned using numbers where:

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.sh

If you want only the file owner to have full access and restrict everyone else entirely, use 700:

chmod 700 script.sh

Verify the Changes

Verify the permission update by running ls -l again:

ls -l script.sh

The 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/bash

Run the Executable Script

Once execution permissions are granted and the shebang is in place, execute the script by specifying its path:

./script.sh

The ./ 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.