How to Write Your First Bash Script

Published 2026-08-05 · Learn Linux

A bash script is a plain-text file that runs commands in order. Write commands in a file, add #!/bin/bash at the top, make it executable with chmod +x, and run it. This guide walks through a complete first script.

Create the script file

Write commands into a file with any editor. The first line, the shebang, tells the system which shell to use. Everything after it runs in order.

$ nano backup.sh

The shebang and a first script

A minimal script prints a message. Put #!/bin/bash on line one, then your commands:

$ echo "Hello, $(whoami)!"

Make it executable

A script will not run until it has execute permission. Set it with chmod, then run it with ./backup.sh. The ./ tells bash to look in the current folder.

$ chmod +x backup.sh
$ ./backup.sh

Add variables and an if statement

Variables make scripts reusable. Assign with NAME=value, read with $NAME, and branch with if:

$ if [ "$(whoami)" = "root" ] ; then echo "Admin mode" ; else echo "Normal user" ; fi

Loop over files

For loops repeat a command for each item. This renames every .txt file:

$ for f in *.txt ; do mv "$f" "${f%.txt}.md" ; done

Schedule the script to run automatically with cron or at. The bash reference page covers the language.

Keep learning

Related guides: Linux chmod Command: A Complete Permissions Guide · How to Schedule Tasks in Linux with cron · The Nano Text Editor: A Beginner's Guide. Read all tutorials on the Learn Linux blog.