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