Skip to content
Linux Basics: Writing a Small Bash Script

Linux Basics: Writing a Small Bash Script

October 8, 2026

A shell script saves a sequence of commands in a text file so you can run it again. This example accepts names as arguments and prints one greeting for each name.

Use Bash on Debian or Ubuntu. Run these examples in order in the same shell:

practice=$(mktemp -d) && cd "$practice"

Continue only if that command succeeds.

Write the script

Save the following code as greet.sh in the practice directory:

#!/bin/bash
if [ "$#" -eq 0 ]; then
  printf 'Usage: bash greet.sh NAME...\n' >&2
  exit 1
fi

for name in "$@"; do
  printf 'Hello, %s!\n' "$name"
done

The first line, #!/bin/bash, identifies Bash as the interpreter. Save the code in the file before running the commands below.

$# is the number of arguments. The if block reports missing arguments on standard error and exits with status one. Spaces around [ and ] are required.

The loop visits every argument. "$@" preserves each argument separately, including spaces inside a name.

Check syntax and run it

bash -n greet.sh && printf 'Syntax OK\n'
Syntax OK

bash -n checks syntax without running the commands. It does not prove the script will behave correctly.

bash greet.sh Ada 'Grace Hopper'
Hello, Ada!
Hello, Grace Hopper!

Invoking bash explicitly only requires the script to be readable; there is no need to make it executable for this exercise.

Try the missing-argument case

bash greet.sh
printf 'status=%s\n' "$?"
Usage: bash greet.sh NAME...
status=1

The first line is standard error; the status line is standard output. Read $? immediately after the script finishes.

Run scripts you understand. A script has the permissions of the account running it, so review its commands before executing it.

Clean up

rm -- greet.sh
cd / && rmdir -- "$practice"
unset practice

Reference

Debian Bash manual

Acknowledgements

This post was created with assistance from AI.

Linux Basics — lesson 25 of 25. Series index

Previous: Understanding File Permission Bits · Next: Practice a complete workflow.

Last updated on