How to Write Your First Bash Script
Create a Bash script file with a shebang line, add a variable and an argument, make it executable with chmod, and run it from the terminal.
A shell script is a text file of commands that Bash runs top to bottom. Create one, make it executable, and run it.
Create the script file
Open a new file called hello.sh in any text editor and put this in it:
#!/bin/bash
echo "Hello"
The first line is the shebang. It tells the system which interpreter runs the file. echo prints its arguments.
Add a variable
#!/bin/bash
name="World"
echo "Hello, $name"
No spaces around = when assigning. Use $name to read the value. Double quotes let the variable expand inside the string; single quotes would print $name literally.
Make the file executable
chmod +x hello.sh
Without this, the system refuses to run the file directly with "Permission denied". You only do this once per file.
Run it
./hello.sh
Hello, World
The ./ tells the shell to look in the current directory; by default it only searches the folders in PATH. Alternatively, bash hello.sh runs the file without needing the executable bit.
Accept an argument
Inside a script, $1 is the first argument on the command line, $2 the second, and so on. Give the variable a default for when no argument is passed:
#!/bin/bash
name="${1:-World}"
echo "Hello, $name"
./hello.sh
./hello.sh everyone
Hello, World
Hello, everyone
$# holds the number of arguments and "$@" holds all of them, which becomes useful once the script grows.
If you want the script to stop on the first error. Add set -e on the line after the shebang. By default Bash keeps going when a command fails, which can turn one bad step into several. set -euo pipefail is the common stricter form: it also treats unset variables as errors and catches failures inside pipelines.
If you are on Windows. Command Prompt and PowerShell do not run Bash scripts. Install Git for Windows, which includes Git Bash, or enable WSL to get a Linux shell, then follow the same steps there.
More Coding how-tos
- How to Add a .gitignore File
- How to Check Which Node.js Version Is Installed
- How to Check Which Python Version Is Installed
- How to Clone a Git Repository
- How to Connect to a Server with SSH
- How to Create a New Git Branch
- How to Create a Python Virtual Environment
- How to Delete a Git Branch
- How to Install Node.js with nvm
- How to Install Python Packages with pip
- How to Make a Script Executable in the Terminal
- How to Print Hello World in JavaScript
- How to Print Hello World in Python
- How to Read a JSON File in Python
- How to Resolve a Merge Conflict in Git
- How to Run a Local Web Server in One Command
- How to Set an Environment Variable
- How to Stash Changes in Git
- How to Undo the Last Git Commit