How to Make a Script Executable in the Terminal
Add a shebang line, give a shell or Python script execute permission with chmod +x, and run it directly with ./script.sh on Mac or Linux.
You wrote a script and running it means typing bash script.sh or python3 script.py every time. Two changes let you run it as ./script.sh instead.
Add a shebang line
The first line of the file tells the system which interpreter should run it. For a shell script:
#!/bin/bash
For a Python script:
#!/usr/bin/env python3
The env form looks up python3 on your PATH, so the script works even when Python is installed in a different location on another machine. The shebang must be the very first line, with no blank line above it.
Give the file execute permission
chmod +x script.sh
chmod changes the file's mode. +x adds the execute bit for the owner, the group, and everyone else. No output means it worked.
Run the script
./script.sh
The ./ matters. When you type a bare command, the shell searches the directories listed in your PATH environment variable, and the current directory is deliberately not one of them. ./ tells the shell to run the file at that exact path. Without it you get command not found even though the file is right there.
Put the script on your PATH
To run the script from any folder without ./, copy it into a directory that is already on PATH, such as /usr/local/bin:
sudo cp script.sh /usr/local/bin/script
Dropping the .sh extension in the destination is common, so the command reads as script from anywhere.
To confirm the permission was set. ls -l script.sh shows the mode at the start of the line. -rwxr-xr-x means executable; -rw-r--r-- means it is not, and chmod +x still needs to run.
On Windows. Windows does not use the execute bit or shebang lines. Run scripts through their interpreter (python script.py) or use .bat and .ps1 files. Inside WSL or Git Bash, the steps above work as written.
More Coding how-tos
- How to Add a .gitignore File
- How to Check Which Node.js Version Is Installed
- How to Check Which Python Version Is Installed
- How to Clone a Git Repository
- How to Create a New Git Branch
- How to Create a Python Virtual Environment
- How to Install Node.js with nvm
- How to Print Hello World in JavaScript
- How to Print Hello World in Python
- How to Run a Local Web Server in One Command
- How to Undo the Last Git Commit