How to Make a Script Executable in Bash: Simple Steps
To make a script executable in bash, use the
chmod +x filename command to add execute permission. Then run it with ./filename to execute the script.Syntax
The basic syntax to make a script executable is:
chmod +x filename: Adds execute permission to the file../filename: Runs the script from the current directory.
bash
chmod +x script.sh ./script.sh
Example
This example shows how to create a simple bash script, make it executable, and run it.
bash
# Create a script file echo '#!/bin/bash' > greet.sh echo 'echo Hello, world!' >> greet.sh # Make the script executable chmod +x greet.sh # Run the script ./greet.sh
Output
Hello, world!
Common Pitfalls
Common mistakes include:
- Not adding execute permission with
chmod +x. - Trying to run the script without specifying
./if the current directory is not inPATH. - Missing the shebang
#!/bin/bashat the top of the script, which tells the system how to run it.
bash
# Wrong: Trying to run without execute permission # ./myscript.sh # bash: ./myscript.sh: Permission denied # Right: Add execute permission and run chmod +x myscript.sh ./myscript.sh
Quick Reference
Summary tips to make scripts executable:
- Use
chmod +x filenameto add execute permission. - Always start scripts with
#!/bin/bashfor clarity. - Run scripts with
./filenameif the current directory is not in yourPATH.
Key Takeaways
Use
chmod +x filename to make your script executable.Run your script with
./filename from the terminal.Include
#!/bin/bash at the top of your script for proper execution.Without execute permission, the script cannot run directly.
The current directory is usually not in
PATH, so use ./ to run scripts there.