Skip to content
DBDeependra Bhatta~/notes
Linux#aws · #bash · #linux · #ec2 · #shell-scripting

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.

· updated · 10 min read
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

SHfirst.sh
#!/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:

terminal
$ chmod +x first.sh
$ ./first.sh
This is my first script

Variables

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.

SHBash
name="dipendra"
echo "Hello, $name"

To keep a variable for every new shell, export it from a startup file:

FileApplies to
~/.bashrcOnly your user, every new interactive shell
/etc/profile or a file in /etc/profile.d/All users, at login
SH.bashrc
~.bashrc
export name=dipendra

Load the change into the current shell with source ~/.bashrc.

Reading input

SHBash
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.

VariableMeaning
$0Name 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)
$HOSTNAMEHost name of the machine
$USERCurrent user
$LINENOCurrent line number in the script
$SECONDSSeconds since the script started
SHargs.sh
#!/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.

SHsysinfo.sh
#!/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

SHBash
if [ condition ]; then
    commands
elif [ other_condition ]; then
    commands
else
    commands
fi

The spaces inside [ and ] are required, because [ is a command and the condition is its arguments. Every if ends with fi.

TestTrue when
-eq, -neNumbers are equal / not equal
-lt, -leLess than / less than or equal
-gt, -geGreater than / greater than or equal
-f pathA regular file exists
-d pathA directory exists
-z "$var"The string is empty
"$a" = "$b"Strings are equal

Example: compare a number with 5

SHcompare.sh
#!/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"
fi

Example: 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:

SHinstall-apache.sh
#!/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
fi
  • set -e stops the script as soon as a command fails.
  • set -u treats an unset variable as an error instead of an empty string.
  • set -o pipefail makes a pipeline fail if any command in it fails, not only the last one.
  • set -x prints each command before it runs, which shows exactly where a script goes wrong.
  • systemctl enable --now enables 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

SHinstall-packages.sh
#!/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"
done

The 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.

SHadd-users.sh
#!/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"
done

The 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

SHcounter.sh
#!/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:

SHec2-v1.sh
#!/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-instances and 100 instances keep running.
  • --security-groups takes 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-instances fails, the script still sleeps and then calls terminate-instances with 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

SHec2-launch-and-terminate.sh
#!/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:

ChangeWhy
set -euo pipefailThe script stops on the first failed command instead of carrying on
Settings from environment variables, with :? for required onesNo hard-coded AMI or network IDs; the script refuses to run if one is missing
trap cleanup EXIT plus trap 'exit 1' INT TERMInstances are terminated however the script ends, including Ctrl+C
read -r -a INSTANCE_IDSStores the IDs in a Bash array, so "${INSTANCE_IDS[@]}" passes each ID as its own argument
--subnet-id and --security-group-idsWork in any VPC, not only the default one
--tag-specifications with a unique run tagIdentifies these instances in the console or with aws ec2 describe-instances --filters Name=tag:run,Values=...
aws ec2 wait instance-runningThe five minutes start once the instances are running
--instance-initiated-shutdown-behavior terminate with shutdown -h +10 in user dataA 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-terminatedThe 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:

terminal
$ 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.sh

For the EC2 basics behind this script (AMIs, key pairs, security groups), see Amazon EC2.

Common mistakes

  • Spaces around = when setting a variable: name = dipendra runs a command called name.
  • Missing spaces inside [ ]: [$a -eq 5] fails; write [ "$a" -eq 5 ].
  • Unquoted variables: $file breaks on names with spaces; use "$file".
  • read -ps: the -p option takes the next letter (s) as its prompt. Write read -s -p "Prompt: " var.
  • Cleanup code at the end of a script runs only if execution reaches it. Put it in a trap ... EXIT handler.

Key takeaways

  • Start scripts with #!/bin/bash and set -euo pipefail; add set -x while 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 trap that deletes them, and tags to find them.

Next in this series: Logical Volume Management (LVM) in Linux.