Bash Scripting from Scratch: Variables, Conditionals, Loops, Functions, and a File-Tidying Script
A Bash script is terminal commands you already know, plus a little logic. This guide covers variables, quoting, conditionals, loops, and functions, and ends with a real file-tidying script: 5 files moved, 3 txt and 2 md, inbox left at 0. Bash builtins only, GNU Bash 5.2.21.

Every day on a computer there are small chores that repeat: sorting the files in the downloads folder, checking how much the shop sold today, filing away a pile of loose notes. Doing them by hand works, but doing them every day gets old. A Bash script is a file that holds those repeated steps so the computer can run them for you, over and over. This guide starts from zero: variables, conditionals, loops, and functions, ending with a real, usable script that tidies files. Everything uses Bash builtins only — no third-party packages. The code was actually run on GNU Bash 5.2.21; the demo script is demo244_zh.sh in the draft folder (Chinese version) and the English rerun is rerun_en_demo244_g1.sh, and both produce the same numbers. The examples use a fictional "Morning Bookstore" to tie everything together; the numbers are all measured values from the demo scripts.
First, what is Bash? Every command you type in a terminal — ls, cd, mkdir — is executed by Bash. Write those commands in order into a file, let Bash run them one by one, and that file is a Bash script. The payoff is "write once, run forever": tidy 5 files today, tidy 50 tomorrow, with the same script and no extra typing. You do not need to learn a "big language" first. Scripting is mostly chaining together terminal commands you already know, plus a little logic for decisions and repetition.
Run it first: the first line and execute permission
Create a file called hello.sh with these two lines:
#!/usr/bin/env bash
echo "Hello, Morning Bookstore"
The first line is called the shebang. It tells the system "run this file with Bash". The second line, echo, just prints a sentence. After writing it, give the file execute permission and run it:
chmod +x hello.sh
./hello.sh
What it does: chmod +x tags the file as "allowed to execute" — without it, the system refuses to run it. The ./ in ./hello.sh says "run this file right here in the current directory"; without it the system looks elsewhere and reports that it cannot find the file. Why it is written this way: a script file starts life as an ordinary text file, so you have to state explicitly that it may run and where to find it. Both steps are required. Beginners most often get stuck here — the file is correct, they forgot chmod +x, and then they doubt everything.
Variables: giving data a name
A variable is a name for a value, so you can use the name later instead of the value. Section 1 of the demo script looks like this:
shop="Morning Bookstore"
price=36
qty=3
total=$((price * qty))
echo "Shop: $shop"
echo "Unit price ${price} yuan x ${qty} books = ${total} yuan"
What it does: it stores the shop name in shop, the unit price 36 in price, the quantity 3 in qty, then does the arithmetic with $((...)) — 36 times 3 is 108 — stores it in total, and prints two lines. The measured output is "Shop: Morning Bookstore" and "Unit price 36 yuan x 3 books = 108 yuan". Why it is written this way: $((...)) is Bash's arithmetic expansion, where * means multiply; you read a variable back by putting $ in front of its name, as in $shop; the braces in ${price} fence the variable name off so it cannot be confused with the Chinese text that follows. Remember three rules: first, no spaces around = in an assignment — price = 36 fails, because Bash treats price as a command name; second, a variable name may only contain letters, digits, and underscores, and may not start with a digit; third, numbers need no quotes, while text usually needs quotes, especially text with spaces in it.
Single quotes vs double quotes: one character, a different result
This is the easiest trap in Bash, so section 2 of the demo compares the two directly:
name="Xiaoming"
echo "Double quotes expand variables: Hello, $name"
echo 'Single quotes do not expand variables: Hello, $name'
What it does: the first line prints "Double quotes expand variables: Hello, Xiaoming", and the second prints the literal text "Single quotes do not expand variables: Hello, $name". Why it is written this way: inside double quotes, $name is replaced with the variable's value; inside single quotes, Bash touches nothing and prints the text exactly as written. How to choose: use double quotes when you want variables to take effect, single quotes when you want the text kept verbatim. The safest habit is to wrap any string that contains a variable in double quotes, like "$shop". One more detail: prefer "$name" over a bare $name, because if the value ever contains a space, the unquoted form gets split into several pieces — you will see that trap for real in the loop section below.
Conditionals: letting the script decide for itself
Half the value of a script is automation; the other half is judgement. Section 3 of the demo first judges the day's sales, then checks whether a file exists:
sales=1286
if (( sales >= 1000 )); then
echo "Today's sales: ${sales} yuan — a good day"
elif (( sales >= 500 )); then
echo "Today's sales: ${sales} yuan — an okay day"
else
echo "Today's sales: ${sales} yuan — a quiet day"
fi
What it does: sales are 1286, which is at least 1000, so the first branch runs and prints "Today's sales: 1286 yuan — a good day". Why it is written this way: if ... then ... elif ... else ... fi is a fixed structure, and fi is just if spelled backwards, marking the end of the test; (( ... )) with double parentheses is for number comparisons, where you can write >=, <, and == just like in maths class. Use (( )) for numbers and [ ] for text, for example [ "$shop" = "Morning Bookstore" ], with spaces on both sides inside the brackets — another spot where beginners slip.
Checking whether a file exists is one of the most common tests in scripts:
if [ -f /tmp/demo244_bash_marker.txt ]; then
echo "Marker file exists"
else
echo "Marker file does not exist (expected on a fresh run)"
fi
What it does: -f asks "is this path a real file?" On the first run the file has not been created yet, so it prints "Marker file does not exist"; the script then creates the file with touch, tests again, and prints "file exists". Why it is written this way: asking "is it there?" before touching a file prevents most errors. Other handy tests are -d (is it a directory?), -z (is the string empty?), and ! (negation). To keep the output identical on every run, the demo script deletes this marker file at the start, so you will see the same two lines each time you run it.
Loops: handing repetition to the computer
A loop is "the same thing, repeated". Section 4 of the demo uses a for loop to add up four books' sales:
sum=0
for n in 12 8 15 5; do
sum=$((sum + n))
done
echo "Four books sold 12, 8, 15 and 5 copies; total: ${sum} books"
What it does: sum starts at 0, the loop takes 12, 8, 15, and 5 in turn, adds each to sum, and finally prints "Four books sold 12, 8, 15 and 5 copies; total: 40 books". Why it is written this way: for n in ... hands each value in the list to n in turn, and the loop body works with n; done marks the end of the loop. 12 plus 8 plus 15 plus 5 is 40, and that is the total shown in the chart below.

Section 5 is a while loop, for when you do not know how many times to repeat, only when to stop:
count=3
while (( count > 0 )); do
echo "Countdown ${count}"
count=$((count - 1))
done
echo "Open for business!"
What it does: it counts down from 3, printing "Countdown 3", "Countdown 2", "Countdown 1", then stops at 0 and prints "Open for business!" Why it is written this way: while means "keep going as long as the condition holds", so the loop body must contain a step that eventually makes the condition false — here count=$((count - 1)) subtracts 1 each round. Forgetting that step is the classic while mistake: the condition stays true forever, the loop never stops, and only Ctrl+C can break out. How to choose: a fixed count or a ready-made list calls for for; a stop condition calls for while.
Functions: packaging steps you reuse
When the same logic is needed in several places, pack it into a function. Section 6 of the demo defines two:
discount() {
local amount=$1
local rate=$2
echo $((amount * rate / 10))
}
after=$(discount 200 8)
echo "200 yuan at 20% off: ${after} yuan"
What it does: discount takes two arguments, works out 200 yuan at 20 percent off as 160, and $(...) captures the function's output into after, printing "200 yuan at 20% off: 160 yuan". Why it is written this way: $1 and $2 are the function's first and second arguments; local declares "this variable only lives inside the function" — without it, the variable leaks out and can collide with a same-named variable elsewhere; the function prints its result with echo, and the caller catches it with $(discount 200 8), which is the most common way for a Bash function to "return" a value.
Functions have a second use: answering just "yes or no", for use inside an if:
is_big() {
if (( $1 >= 1000 )); then
return 0
else
return 1
fi
}
if is_big 1286; then
echo "is_big 1286: returns 0 (in Bash, 0 means success / yes)"
fi
What it does: is_big 1286 returns 0, so the if treats it as true and prints the explanation; is_big 300 returns 1, so the if treats it as false and the else prints "is_big 300: returns 1 (no)". Why it is written this way: Bash's convention is the opposite of intuition — returning 0 means success, or "yes", and returning non-zero means failure, or "no". It comes from Unix exit codes: a command that finished cleanly returns 0, and one that failed returns a non-zero number saying what went wrong. Nine out of ten beginners trip over this once; just remember "0 is good news". You can also read a return code on its own with $?, but $? only holds the previous command's result — one more command and it changes — so use it immediately.
Putting it together: a real script that tidies files
All the pieces from the first six sections are ready. Now they combine into a script that genuinely helps: count the files in an inbox by extension and move them all into an archive folder. Section 7 of the demo is exactly that:
workdir="/tmp/demo244_bash"
rm -rf "$workdir"
mkdir -p "$workdir/inbox" "$workdir/archive"
touch "$workdir/inbox/order1.txt" "$workdir/inbox/order2.txt" "$workdir/inbox/order3.txt"
touch "$workdir/inbox/note1.md" "$workdir/inbox/note2.md"
moved=0
txt=0
md=0
for f in "$workdir"/inbox/*; do
case "$f" in
*.txt) txt=$((txt + 1)) ;;
*.md) md=$((md + 1)) ;;
esac
mv "$f" "$workdir/archive/"
moved=$((moved + 1))
done
echo "Inbox started with 5 files: txt ${txt}, md ${md}"
echo "Moved ${moved} files to archive; inbox now has: $(ls "$workdir/inbox" | wc -l)"
echo "Archive now holds: $(ls "$workdir/archive" | wc -l) files"
What it does: it sets up an inbox and an archive folder, puts 5 sample files in the inbox (3 txt, 2 md), then loops over them one by one: case counts them by suffix, mv moves each file into the archive, and three lines report the result. The measured output is "Inbox started with 5 files: txt 3, md 2", "Moved 5 files to archive; inbox now has: 0", and "Archive now holds: 5 files". Why it is written this way: the * in for f in "$workdir"/inbox/* is a wildcard meaning "every file in this directory"; case ... in *.txt) branches on the suffix and is cleaner than a chain of ifs; counting and moving are separate steps, so if the move ever fails, the count is not corrupted with it. With small changes this script is genuinely usable: replace /tmp/demo244_bash/inbox with your own downloads folder, swap *.txt and *.md for the categories you want, and add a step that creates a subfolder by date. Note the line rm -rf "$workdir" at the top: it exists so the demo starts from a clean state every time. When you adapt this into your own script, never copy that line as-is against a real folder — deleting the wrong thing cannot be undone.
Going further: letting the script take arguments
The tidy script has one flaw: the folder is hard-coded, so changing folders means editing the script. Command-line arguments fix that. In Bash, $1 is the first argument, $2 the second, and $# the number of arguments. For example:
#!/usr/bin/env bash
if [ $# -lt 1 ]; then
echo "Usage: $0 folder"
exit 1
fi
target="$1"
echo "Folder to tidy: $target"
ls "$target"
What it does: it counts the arguments first; with fewer than 1 it prints the usage and exits; otherwise it stores the first argument in target and lists that folder's contents. Why it is written this way: $0 is the script's own name, so the usage message stays correct even if someone renames the script; exit 1 quits deliberately and tells the caller "I failed" — a non-zero exit code is the report; [ $# -lt 1 ] uses -lt for "less than", because inside single brackets, number comparisons use -lt, -gt, and -eq, not <. Put these lines in front of section 7's tidy script, replace the hard-coded inbox path with the "$1" folder, and the demo becomes a tool: pass the downloads folder to tidy downloads, pass the desktop to tidy the desktop. You can take more than one argument too — the first as the source folder, the second as the archive folder — and check at the top that $# equals 2, printing the usage otherwise. Collect three or five such small tools and your daily repeated chores are mostly automated.
Three debugging moves for when a script goes sideways
When a script misbehaves, do not just stare at it — use these three moves to find the fault. First, bash -x: run bash -x demo244_zh.sh and Bash prints every line before executing it, prefixed with a plus sign, so you can see at a glance where it first diverges from what you expected and what each variable held at that moment. Second, sprinkle in echo at key points: a line like echo "Now handling: $f" inside the loop shows how many rounds the loop ran and which file each round handled — the problem is often hiding in one particular round. Third, set -e: put it at the top of the script and it means "stop immediately if any line fails", instead of carrying on with the error and leaving a pile of confusing results. The demo script uses set -u, which means "error out if an undefined variable is used" — the same kind of safety net: fail early and loudly rather than letting a mistake slip quietly past. One more down-to-earth trick: copy the few suspicious lines out of the script and type them one by one in the terminal; whichever line errors is where the problem lives. Debugging a script has no shortcut — shrink the area of suspicion until only one place is left.
Five traps beginners hit most
The first trap is spaces around =: price=36 is right, price = 36 is wrong — Bash treats price as a command name and reports that it cannot be found. The second is quotes: double quotes to expand variables, single quotes to keep text verbatim, and write variable reads as "$name" whenever you can, so values with spaces are not split apart. The third is the timing of $?: it only holds the previous command's exit code, and any command in between overwrites it, so use it right away. The fourth is forgetting chmod +x: if a script that looks right will not run, check execute permission first. The fifth is forgetting to change the condition inside a while loop: the loop body must contain a step that eventually makes the condition false, or it is an infinite loop that only Ctrl+C can stop. The demo script contains the correct form for each of these — compare and fix against it.
One more detail that is easy to miss: line endings. A text file edited on Windows may carry an invisible carriage return at the end of each line, and Bash will report strange errors, such as a command not found or a stray $'\r' at the end of a line. If you see that, first check your code — no, check the file: run cat -A scriptname and look for ^M at the ends of lines. If it is there, the line endings are the problem, and dos2unix or sed -i 's/\r$//' scriptname will convert them. Files created directly on Linux or macOS do not usually have this problem, but any script copied over from Windows is worth checking first.
One small script a day: where to find the next task
After learning the syntax, the hardest part is "what do I write?" The topics are already in your daily routine: the notes folder you back up every week, the disk usage you glance at each day, the list of files you check before every release. Pick one thing you have repeated three times this week and script it. The first version does not need to be perfect — running at all is a win; add checks, arguments, and messages afterwards. Many people learn Bash backwards, reading the whole manual before touching the keyboard; the other way round works better. Write a ten-line script that solves one real chore, and when you get stuck, look up just that one section of the manual. What you learn is used immediately, and it sticks. Once you have three or five such scripts, variables, conditionals, loops, and functions stop being textbook concepts and become tools you reach for daily. And when you go back to the GNU Bash manual then, it will no longer read like a foreign language — it will read like a dictionary you can dip into at will.
Scope and next steps
This guide covers only the five beginner pieces — variables, quotes, conditionals, loops, and functions — plus one script that assembles them. Not covered: arrays, getopts argument parsing, signal handling, and parallel execution. Those are intermediate topics, best learned after you have run this guide's script for real and adapted it into your own version. Suggested next step: turn section 7's tidy script into your own version, with a real folder and real categories, and run it for a week; then add one feature — for example, check whether the destination file already exists before moving, skip it, and log a line when you do. Those small changes will make you practise conditionals and loops a few more times, which beats reading ten more pages of documentation. The biggest trick in writing scripts is a simple one: type each step by hand in the terminal first, confirm every step works, and only then copy those commands into a file and add the decisions and loops. A script is not written out of thin air — it is a collection of commands that have already been run successfully.
Comments (0)
Sources
Related articles
tmux 3.4, zero packages: 1 session, 2 windows, 3 panes; the logs window prints 1 to 5, editor panes report ready. Detach with Ctrl-b d, reattach with tmux attach — the session outlives the connection. Mouse, prefix key and history limit in ~/.tmux.conf included.
6 files, 24 lines, 4 TODO lines; false | true gives PIPESTATUS 1 and 0, pipefail on exits 1, off exits 0; a spaced filename splits into 2 words unquoted, 1 quoted; backup 6 files, 445 bytes. Bash 5.2.21, measured.
GCC 13.3.0, C17, zero packages: a first C program, sizeof results 1/2/4/8/8/4/8/8, sum 1..100 is 5050, 10! is 3628800, 8 numbers sorted, 3 books total 1088 pages, 3 file lines and 70 chars read back. Preprocessing alone expands 3 lines to 815.