0
0
Bash-scriptingHow-ToBeginner · 3 min read

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 .sh but 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!"
date
Output
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

CommandPurpose
#!/bin/bashSpecify bash interpreter
chmod +x script.shMake script executable
./script.shRun the script from current directory
echoPrint text to the screen
# commentAdd 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.