Shebang / chmod +x
A shebang is a special comment written on the first line of a script file that specifies which interpreter to use. By granting execute permission with chmod +x, you can run the script directly.
Syntax
Shebang. Declares that this script should be run with /bin/bash.
#!/bin/bash
Finds bash via env (portable style that avoids hard-coded paths).
#!/usr/bin/env bash
Grant execute permission to a script.
chmod +x script_filename
Run directly (shebang required).
./script_filename
Run with the bash command (no shebang or execute permission needed).
bash script_filename
Common Shebangs
| Shebang / Command | Description |
|---|---|
| #!/bin/bash | Runs with the Bash shell. The most common form. |
| #!/usr/bin/env bash | Finds bash via PATH and runs it. Recommended for macOS and nvm environments. |
| #!/bin/sh | Runs with a POSIX-compliant shell. Use this when maximum portability is the priority. |
| #!/usr/bin/env python3 | Runs with Python 3. |
| #!/usr/bin/env node | Runs with Node.js. |
| #!/usr/bin/env php | Runs with PHP. |
| chmod +x file | Grants execute permission to all users. |
| chmod 755 file | Grants rwx to the owner and r-x to group and others. |
| chmod 700 file | Grants execute permission to the owner only (others cannot execute). |
Sample Code
Create a file called hello.sh with the following content.
hello.sh
#!/usr/bin/env bash
# hello.sh — A basic shell script template
echo "Script name: $0"
echo "Number of arguments: $#"
echo "All arguments: $@"
if [ $# -eq 0 ]; then
echo "Usage: $0 name" >&2
exit 1
fi
echo "Hello, $1!"
Grant execute permission to the script.
chmod +x hello.sh
Checking the permissions, you can see that x (execute permission) is now set.
ls -l hello.sh -rwxr-xr-x 1 user user 42 Mar 6 12:00 hello.sh
With the shebang and execute permission in place, you can run the script directly using ./.
./hello.sh Alice Script name: ./hello.sh Number of arguments: 1 All arguments: Alice Hello, Alice!
When running with the bash command, neither execute permission nor a shebang is required.
bash hello.sh Bob Script name: hello.sh Number of arguments: 1 All arguments: Bob Hello, Bob!
Notes
The shebang must be written on the first line of the file. A blank line or BOM (Byte Order Mark) before it will make it ineffective. To avoid environment-specific issues, the #!/usr/bin/env bash form is recommended.
chmod +x marks a file as executable. Running a script with ./ requires execute permission, but specifying the interpreter explicitly — as in bash script_name — works without it. See also Special Variables for details on how variables and arguments are handled inside scripts.
If you find any errors or copyright issues, please contact us.