Shell Scripting

Bash Scripting Basics — Variables, Loops, Conditionals, and Functions

A bash script is a text file of commands that the shell runs in order, and five building blocks cover most of what a first script needs. A variable holds a value. A for loop repeats a block once per item in a list. A while loop repeats while a test passes. An if runs a block only when its test passes. A function groups commands under a name and takes inputs as positional parameters. This guide builds each block in small scripts with exact output, then shows the two traps that stop most first scripts: spaces around the equals sign in an assignment, and an unquoted variable inside a test.

Written November 12, 2026 · 9 min read

By the end of this guide
  • The main program: all five blocks in one script
  • Variables: no spaces around the equals sign
  • for: one pass per item in a list
  • while: repeat while a test passes

Written November 12, 2026

Tested with GNU bash 5.2.21

What this guide is

Bash is the shell that runs your commands in a terminal, and a script is those commands saved in a file so they can run again as one unit. The first line of a script, called the shebang, names the program that should run the file. The line #!/bin/bash names bash. Saving the commands is not enough on its own: the file also needs the executable bit before it can be run by name, which chmod +x sets. After that step, ./main.sh runs the file the same way bash main.sh does, with the shebang choosing the interpreter. The five blocks below, variables, two loops, a conditional, and a function, are the whole skeleton of a working script.

The main program: all five blocks in one script

Bash
#!/bin/bash
name="veldica"
count=3
echo "name=$name count=$count"
for i in 1 2 3; do
  echo "loop i=$i"
done
n=2
while [ $n -gt 0 ]; do
  echo "while n=$n"
  n=$((n - 1))
done
if [ "$name" = "veldica" ]; then
  echo "name matches"
fi
greet() { echo "hello $1"; }
greet "world"

The exact output:

Output
name=veldica count=3
loop i=1
loop i=2
loop i=3
while n=2
while n=1
name matches
hello world

Each line of output comes from one block. The assignment lines set two variables, and the first echo reads them back. The for loop prints one line per item in its list. The while loop prints while its counter stays above zero, and the counter drops by one on each pass, which is what makes the loop stop. The if prints because its test passes. The function prints a greeting built from the argument its caller passed. The sections below take each block in turn.

Variables: no spaces around the equals sign

An assignment is a name, an equals sign, and a value, written as one word with no spaces: name="veldica". Reading the variable back takes a dollar sign: $name expands to the value the variable holds. Quotes around a value keep it as one unit even when it holds spaces, and quotes around an expansion do the same job at the point of use:

Bash
#!/bin/bash
greeting="hello world"
echo "quoted:"
printf '%s\n' "$greeting"
echo "unquoted:"
printf '%s\n' $greeting

The exact output:

Output
quoted:
hello world
unquoted:
hello
world

The quoted expansion reaches printf as one argument, so it prints on one line. The unquoted expansion is split into words first, so printf receives two arguments and prints each on its own line. That split is called word splitting, and it is the reason the standing rule exists: quote every expansion, "$name", unless the split is the effect you want. A variable that has never been assigned expands to nothing, an empty string, which matters in the test trap below.

for: one pass per item in a list

A for loop takes each item from a list in order, assigns it to the loop variable, and runs the block between do and done once per item:

Bash
#!/bin/bash
for tool in bash grep sed awk; do
  echo "tool=$tool"
done
count=0
for tool in bash grep sed awk; do
  count=$((count + 1))
done
echo "count=$count"

The exact output:

Output
tool=bash
tool=grep
tool=sed
tool=awk
count=4

The list here is four words written in the loop line. The same shape walks the words in a variable, the files a pattern matches, or the lines of output a command produces. The second loop shows the counting pattern: start a counter at zero, add one per pass with $((count + 1)), and read the total after the loop ends. The form $((...)) is arithmetic expansion: bash works out the sum inside the parentheses and substitutes the number.

while: repeat while a test passes

A while loop runs its block as long as its test passes, and checks the test again before every pass. The main program used it as a countdown: while [ $n -gt 0 ] passes while n is greater than zero, and the body lowers n by one each pass, so the loop runs twice and then stops. A while loop whose body never changes the tested value never stops, so the line that moves the counter is not decoration. The test itself is the command between the keyword and do, most often the [ ... ] form the next section covers. Any command can stand there: the loop runs while the command succeeds, which is a status of zero, and stops when it fails.

if and tests: quote the variable

An if runs its block when its test passes and skips it when the test fails. The common test form is [ ... ], a command that compares values: [ "$name" = "veldica" ] passes when the variable holds that exact string, and [ $n -gt 0 ] passes when the number is greater than zero. String tests use = and numeric tests use words such as -gt, -lt, and -eq, because > inside a test would mean redirection to a file, not comparison.

Quoting the variable inside a test is the difference between a clean answer and an error. With an empty variable, the quoted form still has an operand on each side of the equals sign:

Bash
#!/bin/bash
name=""
if [ "$name" = "veldica" ]; then
  echo "matches"
else
  echo "no match"
fi

The exact output:

Output
no match

Drop the quotes and the empty expansion vanishes from the command line. The test becomes [ = "veldica" ], which has no left operand, and bash reports the exact error [: =: unary operator expected before treating the test as failed. The script still prints no match, but for the wrong reason: the test broke instead of answering. Any variable that can be empty, a name read from input, a path that may not be set, needs quotes inside a test.

Functions: positional parameters and exit status

A function groups commands under a name. The definition greet() { echo "hello $1"; } builds a function whose body runs when a caller writes greet "world". Inside the body, $1 is the first argument the caller passed, $2 the second, and so on. Those names are the positional parameters, and they belong to the call, so two calls with different arguments run the same body on different values:

Bash
#!/bin/bash
add() {
  echo $(($1 + $2))
}
total=$(add 2 3)
echo "total=$total"
[ "$total" = "5" ]
echo "test status=$?"
[ "$total" = "6" ]
echo "test status=$?"

The exact output:

Output
total=5
test status=0
test status=1

The add function prints the sum of its two arguments, and the $(...) form around the call, command substitution, captures that printed value into the variable total. A function hands a value back to a caller in exactly this way, by printing it for capture, or by its exit status. The status is the number in $?, read right after a command runs: zero means the command succeeded, and any other number means it failed. The first test above passes, so its status is 0. The second test fails, so its status is 1. That number is what if and while read when their test is a command, which is why a test and a status are the same mechanism seen from two sides.

Trap: spaces around the equals sign

Trap
The most common first-script error is an assignment written the way it would be read aloud:
Bash
name = "veldica"

Bash does not read that line as an assignment at all. With spaces, the line is a command: run the program named name with two arguments, = and veldica. No such program exists, so the run fails with the exact error name: command not found and an exit status of 127, the status bash uses when a command is not found. The variable is never set, and a script without an error stop keeps going with name empty, which then breaks a later test in the way the previous section showed. The fix is the form from the variables section: name="veldica", one word, no spaces on either side of the equals sign.

Which block for which job

Job Block Why
A value the script uses more than once A variable, as in name="veldica" One assignment updates every use
A value with spaces kept as one unit A quoted expansion, "$name" Word splitting cannot break it into pieces
One pass per item in a known list A for loop The list states the items and the count up front
Repeat until a value changes enough A while loop with a counter step The test is rechecked before every pass, and the step makes it stop
Run a block only when a condition holds An if with a [ ... ] test The test states the condition in one line
A comparison against a value that may be empty A quoted test, [ "$name" = "veldica" ] The test still has both operands when the variable is empty
The same commands called from two places A function with positional parameters One body, called with different arguments
A result a caller needs as a value A function that prints, captured with $(...) The printed output becomes the caller's variable
A check on whether the last command worked $? read immediately after it Zero is success, any other number is the failure the command reported

Checklist

  • Before running a script by name, confirm the first line is the shebang #!/bin/bash and the file has its executable bit set with chmod +x.
  • Before writing an assignment, check that the name, the equals sign, and the value form one word with no spaces.
  • Before using a variable, quote its expansion, "$name", unless word splitting is the effect you want.
  • Before writing a while loop, point at the line inside the body that changes the tested value; a loop without that line never stops.
  • Before testing a variable that can be empty, quote it inside the brackets so the test keeps both operands.
  • Before repeating a block of commands in a second place, name it as a function and pass the differing values in as arguments.
  • Before reading $?, confirm no other command ran in between; the number always describes the most recent command only.

Sources

Keep Exploring