How to Run a Bash Script: Simple Steps and Examples
To run a bash script, use the command
bash scriptname.sh or make the script executable with chmod +x scriptname.sh and run it with ./scriptname.sh. This executes the commands inside the script file in a bash shell.Syntax
There are two main ways to run a bash script:
- Using bash command: Runs the script with the bash interpreter explicitly.
- Using executable permission: Makes the script file executable and runs it directly.
Syntax details:
bash scriptname.sh: Runs the script with bash.chmod +x scriptname.sh: Adds execute permission../scriptname.sh: Runs the script if it has execute permission.
bash
bash scriptname.sh chmod +x scriptname.sh ./scriptname.sh
Example
This example script prints a greeting message. It shows how to run a bash script using both methods.
bash
#!/bin/bash
# greeting.sh
echo "Hello, welcome to bash scripting!"Output
Hello, welcome to bash scripting!
Common Pitfalls
Common mistakes when running bash scripts include:
- Not giving execute permission before running with
./scriptname.sh. - Trying to run the script without specifying the interpreter if the shebang (
#!/bin/bash) is missing. - Running the script with
./but the current directory is not in the PATH.
bash
# Wrong: Trying to run without execute permission ./greeting.sh # Right: Add execute permission first chmod +x greeting.sh ./greeting.sh
Quick Reference
Summary tips for running bash scripts:
- Use
bash scriptname.shto run without changing permissions. - Use
chmod +x scriptname.shand./scriptname.shfor direct execution. - Always start scripts with
#!/bin/bashfor portability. - Check file permissions with
ls -l.
Key Takeaways
Run a bash script using
bash scriptname.sh or make it executable and run with ./scriptname.sh.Add execute permission with
chmod +x scriptname.sh before running directly.Include
#!/bin/bash at the top of your script for proper interpreter usage.Check and fix permissions if you get 'Permission denied' errors.
Use the current directory prefix
./ to run scripts not in your PATH.