How to Create a Bash Script: Simple Steps for Beginners
To create a
bash script, write your commands in a plain text file starting with #!/bin/bash on the first line, then save it with a .sh extension. Make the file executable using chmod +x filename.sh and run it with ./filename.sh.Syntax
A bash script starts with a shebang line #!/bin/bash which tells the system to use the bash shell to run the script. Below that, you write the commands you want to automate, one per line. Save the file with a .sh extension for clarity.
- #!/bin/bash: Specifies bash as the interpreter.
- Commands: Any bash commands you want to run.
- File extension: Usually
.shbut not mandatory.
bash
#!/bin/bash # This is a comment command1 command2
Example
This example script prints a greeting message and the current date. It shows how to write commands and run the script.
bash
#!/bin/bash
echo "Hello, friend!"
dateOutput
Hello, friend!
Fri Jun 21 12:00:00 UTC 2024
Common Pitfalls
Common mistakes include forgetting the shebang line, not making the script executable, or using Windows-style line endings which can cause errors on Linux. Also, running the script without ./ if the current directory is not in your PATH can cause "command not found" errors.
bash
# Wrong: Missing shebang echo "Hello" # Right: Include shebang and make executable #!/bin/bash echo "Hello"
Quick Reference
| Command | Purpose |
|---|---|
| #!/bin/bash | Specify bash interpreter |
| chmod +x script.sh | Make script executable |
| ./script.sh | Run the script from current directory |
| echo | Print text to the screen |
| # comment | Add comments in script |
Key Takeaways
Start your bash script with #!/bin/bash to specify the interpreter.
Save the script as a plain text file with a .sh extension for clarity.
Make the script executable using chmod +x before running it.
Run the script with ./filename.sh if the current directory is not in PATH.
Avoid Windows line endings and always test your script after writing.