How to Write Your First Bash Script
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.
The shebang and a first script
A minimal script prints a message. Put #!/bin/bash on line one, then your commands:
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.
Add variables and an if statement
Variables make scripts reusable. Assign with NAME=value, read with $NAME, and branch with if:
Loop over files
For loops repeat a command for each item. This renames every .txt file:
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.