Bash Shell Scripting Basics with an EC2 Automation Script
Bash scripting from first script to loops: variables, input, arguments, command substitution, if, for and while, ending with a safe script that launches and cleans up EC2 instances.

ON THIS PAGE
Any task typed twice on a server, such as installing packages, adding users or creating cloud resources, is a candidate for a shell script. This part builds up Bash from a first script through variables, arguments, conditions and loops. It ends with a script that launches 100 EC2 instances and guarantees they are terminated five minutes later, even if the script is interrupted.
Your first script
#!/bin/bash
echo "This is my first script"The first line is the shebang: #! followed by the interpreter that should run the file, here /bin/bash. Make the script executable, then run it:
$ chmod +x first.sh
$ ./first.sh
This is my first scriptVariables
Inside a script, set a variable with name=value (no spaces around =) and read it with $name. Quote it as "$name" so values with spaces stay in one piece.
name="dipendra"
echo "Hello, $name"To keep a variable for every new shell, export it from a startup file:
| File | Applies to |
|---|---|
~/.bashrc | Only your user, every new interactive shell |
/etc/profile or a file in /etc/profile.d/ | All users, at login |
export name=dipendraLoad the change into the current shell with source ~/.bashrc.
Reading input
read -p "Enter your name: " username
read -s -p "Enter your password: " password
echo-p shows a prompt. -s (silent) hides what the user types, which is required for passwords. The empty echo prints a new line, because -s also hides the Enter key.
Special variables and arguments
Arguments are the values you pass after the script name, for example ./deploy.sh staging v2.
| Variable | Meaning |
|---|---|
$0 | Name or path of the script |
$1, $2, ... | First, second, ... argument |
$@ | All arguments, as separate words (use "$@") |
$# | Number of arguments |
$? | Exit code of the last command (0 means success) |
$HOSTNAME | Host name of the machine |
$USER | Current user |
$LINENO | Current line number in the script |
$SECONDS | Seconds since the script started |
#!/bin/bash
echo "Script: $0"
echo "First argument: $1"
echo "All arguments: $@"
echo "Number of arguments: $#"
sleep 5
echo "Ran for $SECONDS seconds on $HOSTNAME as $USER"Command substitution
Command substitution runs a command and puts its output in its place. Write it as $(command). The older backtick form `command` still works, but $(...) is easier to read and can be nested.
#!/bin/bash
ipadd=$(ip -4 addr show)
echo "$ipadd"
ip=$(hostname -I | awk '{print $1}')
echo "Main IP: $ip"
disk=$(df -h)
echo "$disk"
diskusage=$(du -sh *)
echo "$diskusage"
apachestatus=$(grep apache2-data /var/log/dpkg.log)
echo "$apachestatus"Quote the variable when you print it. echo $disk without quotes joins all lines into one long line.
Conditions with if
if [ condition ]; then
commands
elif [ other_condition ]; then
commands
else
commands
fiThe spaces inside [ and ] are required, because [ is a command and the condition is its arguments. Every if ends with fi.
| Test | True when |
|---|---|
-eq, -ne | Numbers are equal / not equal |
-lt, -le | Less than / less than or equal |
-gt, -ge | Greater than / greater than or equal |
-f path | A regular file exists |
-d path | A directory exists |
-z "$var" | The string is empty |
"$a" = "$b" | Strings are equal |
Example: compare a number with 5
#!/bin/bash
read -p "Please enter a number to check: " num
if [ "$num" -eq 5 ]; then
echo "$num is equal to 5"
elif [ "$num" -lt 5 ]; then
echo "$num is less than 5"
else
echo "$num is greater than 5"
fiExample: install Apache only if it is missing
My first version checked for Apache's PID file in /var/run/apache2/. That file exists only while Apache is running, so a stopped Apache was reported as "not installed". Querying the package database with dpkg -s is reliable:
#!/bin/bash
set -euo pipefail
set -x
if dpkg -s apache2 > /dev/null 2>&1; then
echo "apache2 is already installed"
else
echo "apache2 is not installed, installing it"
sudo apt-get update
sudo apt-get install -y apache2
sudo systemctl enable --now apache2
fiset -estops the script as soon as a command fails.set -utreats an unset variable as an error instead of an empty string.set -o pipefailmakes a pipeline fail if any command in it fails, not only the last one.set -xprints each command before it runs, which shows exactly where a script goes wrong.systemctl enable --nowenables the service at boot and starts it right away.
To test the else branch, remove Apache first with sudo apt purge -y apache2 && sudo apt autoremove -y.
Loops
for: when you know the list
#!/bin/bash
set -euo pipefail
pkgs=(wget curl git apache2)
sudo apt-get update
for pkg in "${pkgs[@]}"; do
echo "Installing package $pkg"
sudo apt-get install -y "$pkg"
doneThe package list is a Bash array. "${pkgs[@]}" expands to each item as a separate word. apt-get update runs once before the loop, because repeating it for every package adds time without benefit.
#!/bin/bash
set -euo pipefail
for user in ram shyam hari; do
if id "$user" > /dev/null 2>&1; then
echo "User $user already exists, skipping"
continue
fi
echo "Adding user $user"
sudo useradd -m "$user"
id "$user"
doneThe id check makes the script safe to run twice. Without it, useradd fails on the second run and set -e stops the script. Users and useradd options are covered in Linux Users, Permissions and Package Management.
while: when you loop until a condition changes
#!/bin/bash
counter=0
while [ "$counter" -lt 5 ]; do
echo "The value of counter is $counter"
counter=$((counter + 1))
sleep 2
done
echo "We are outside the while loop"This prints 0 to 4. $(( ... )) does integer arithmetic.
Project: launch 100 EC2 instances and terminate them after five minutes
The requirement: launch 100 EC2 instances in parallel and terminate all of them automatically after five minutes. My first version was short:
#!/bin/bash
INSTANCE_IDS=$(aws ec2 run-instances \
--image-id ami-0abcd1234567890 \
--count 100 \
--instance-type t2.micro \
--key-name MyKeyPair \
--security-groups MySecurityGroup \
--query 'Instances[*].InstanceId' \
--output text)
echo "Launched instances: $INSTANCE_IDS"
sleep 300
aws ec2 terminate-instances --instance-ids $INSTANCE_IDS
echo "Terminated instances after 5 minutes."The script works when nothing goes wrong, but several failure modes leave paid resources running:
- If the script stops early (Ctrl+C, a closed SSH session, a laptop going to sleep), it never reaches
terminate-instancesand 100 instances keep running. --security-groupstakes group names and only works in the default VPC. In any other VPC you must pass--security-group-ids(and usually--subnet-id).- No error handling. If
run-instancesfails, the script still sleeps and then callsterminate-instanceswith nothing. - The instances are not tagged, so they are hard to find and clean up by hand.
- The 5-minute timer starts at launch, while the instances are still
pending.
The fixed script
#!/bin/bash
set -euo pipefail
# Settings: override any of these with environment variables.
AMI_ID="${AMI_ID:?Set AMI_ID to an AMI in your region}"
SUBNET_ID="${SUBNET_ID:?Set SUBNET_ID}"
SECURITY_GROUP_ID="${SECURITY_GROUP_ID:?Set SECURITY_GROUP_ID}"
KEY_NAME="${KEY_NAME:-MyKeyPair}"
INSTANCE_TYPE="${INSTANCE_TYPE:-t2.micro}"
COUNT="${COUNT:-100}"
LIFETIME_SECONDS="${LIFETIME_SECONDS:-300}"
RUN_TAG="temp-run-$(date +%Y%m%d%H%M%S)"
INSTANCE_IDS=()
cleanup() {
if [ "${#INSTANCE_IDS[@]}" -gt 0 ]; then
echo "Terminating ${#INSTANCE_IDS[@]} instances..."
aws ec2 terminate-instances --instance-ids "${INSTANCE_IDS[@]}" > /dev/null
aws ec2 wait instance-terminated --instance-ids "${INSTANCE_IDS[@]}"
echo "All instances terminated."
fi
}
# Run cleanup on normal exit, on errors, and on Ctrl+C or kill.
trap cleanup EXIT
trap 'exit 1' INT TERM
echo "Launching $COUNT instances tagged run=$RUN_TAG..."
read -r -a INSTANCE_IDS <<< "$(aws ec2 run-instances \
--image-id "$AMI_ID" \
--count "$COUNT" \
--instance-type "$INSTANCE_TYPE" \
--key-name "$KEY_NAME" \
--subnet-id "$SUBNET_ID" \
--security-group-ids "$SECURITY_GROUP_ID" \
--instance-initiated-shutdown-behavior terminate \
--user-data "$(printf '#!/bin/bash\nshutdown -h +10\n')" \
--tag-specifications "ResourceType=instance,Tags=[{Key=run,Value=$RUN_TAG}]" \
--query 'Instances[*].InstanceId' \
--output text)"
echo "Launched: ${INSTANCE_IDS[*]}"
echo "Waiting until all instances are running..."
aws ec2 wait instance-running --instance-ids "${INSTANCE_IDS[@]}"
echo "All running. Sleeping $LIFETIME_SECONDS seconds..."
sleep "$LIFETIME_SECONDS"
# The EXIT trap terminates the instances here.What changed and why:
| Change | Why |
|---|---|
set -euo pipefail | The script stops on the first failed command instead of carrying on |
Settings from environment variables, with :? for required ones | No hard-coded AMI or network IDs; the script refuses to run if one is missing |
trap cleanup EXIT plus trap 'exit 1' INT TERM | Instances are terminated however the script ends, including Ctrl+C |
read -r -a INSTANCE_IDS | Stores the IDs in a Bash array, so "${INSTANCE_IDS[@]}" passes each ID as its own argument |
--subnet-id and --security-group-ids | Work in any VPC, not only the default one |
--tag-specifications with a unique run tag | Identifies these instances in the console or with aws ec2 describe-instances --filters Name=tag:run,Values=... |
aws ec2 wait instance-running | The five minutes start once the instances are running |
--instance-initiated-shutdown-behavior terminate with shutdown -h +10 in user data | A safety net: even if the machine running the script fails, each instance shuts itself down after 10 minutes, and shutting down means terminate |
aws ec2 wait instance-terminated | The script only reports success once AWS confirms the instances are gone |
--count 100 launches all instances in a single API call, so they start in parallel. A single number means "at least this many": if AWS cannot launch all 100 (for example because of your account's vCPU quota), the call fails and nothing is launched.
Run the script with the required settings:
$ export AMI_ID=ami-0abcd1234567890 SUBNET_ID=subnet-0123456789abcdef0 SECURITY_GROUP_ID=sg-0123456789abcdef0
$ chmod +x ec2-launch-and-terminate.sh
$ COUNT=2 ./ec2-launch-and-terminate.shFor the EC2 basics behind this script (AMIs, key pairs, security groups), see Amazon EC2.
Common mistakes
- Spaces around
=when setting a variable:name = dipendraruns a command calledname. - Missing spaces inside
[ ]:[$a -eq 5]fails; write[ "$a" -eq 5 ]. - Unquoted variables:
$filebreaks on names with spaces; use"$file". read -ps: the-poption takes the next letter (s) as its prompt. Writeread -s -p "Prompt: " var.- Cleanup code at the end of a script runs only if execution reaches it. Put it in a
trap ... EXIThandler.
Key takeaways
- Start scripts with
#!/bin/bashandset -euo pipefail; addset -xwhile debugging. - Quote variables, use
$(...)for command substitution, and use arrays for lists. - Make scripts safe to run twice by checking state first (
dpkg -s,id). - Any script that creates paid cloud resources needs a
trapthat deletes them, and tags to find them.
Next in this series: Logical Volume Management (LVM) in Linux.
Keep reading
- Linux Users, Permissions and Package Management
Manage users, groups, sudo, file permissions, links, apt packages, archives and processes on Ubuntu, with the commands and the files behind each one.
- Essential Linux Commands for DevOps
A task-based Linux command reference: navigating and managing files, reading logs, grep, sed, cut and awk, redirection, Vim, services, and basic networking.
- Introduction to Linux: Kernel, Shell, File System and SSH Login
The Linux foundations behind DevOps work: kernel and shell, distributions, the directory layout, the seven file types, and SSH login to a VirtualBox VM.