Practical examples of examples of variables in shell scripting

When people search for examples of examples of variables in shell scripting, they usually don’t want theory. They want to see real code that actually runs in a terminal and solves real problems. Shell variables are the backbone of every non-trivial script: they hold user input, configuration values, command output, and state that changes as your script runs. In this guide, we’ll walk through practical examples of how variables behave in Bash and other POSIX-style shells, focusing on patterns you’ll use daily: environment variables, positional parameters, command substitution, arrays, and safer quoting. These examples include small, copy‑paste‑ready snippets you can adapt for automation, DevOps, and data-processing tasks in 2024 and beyond. Along the way, you’ll see the best examples of variables in shell scripting that demonstrate not just syntax, but intent: why a variable is defined, how it’s used, and what can go wrong if you skip a detail. If you’ve ever fought with `$PATH`, `$1`, or misquoted variables, this is written for you.
Written by
Jamie
Published
Updated

Quick real‑world examples of variables in shell scripting

Let’s start with concrete, working examples of variables in shell scripting before we worry about the finer points.

Here’s a tiny login‑style greeting script:

#!/usr/bin/env bash

USER_NAME="Alice"
TODAY=$(date +"%Y-%m-%d")

echo "Welcome, $USER_NAME!"
echo "Today is $TODAY."

This simple snippet already shows several examples of variables in shell scripting:

  • USER_NAME is a plain shell variable.
  • TODAY is assigned using command substitution with $(...).
  • Both are expanded inside double quotes with $VAR.

Now a slightly more realistic example of using positional parameters and environment variables together:

#!/usr/bin/env bash

SCRIPT_NAME="$0"      # The script's own name
TARGET_DIR="$1"       # First argument
LOG_LEVEL="${LOG_LEVEL:-info}"  # Environment override with default

echo "Running \(SCRIPT_NAME on directory: \)TARGET_DIR"
echo "Log level: $LOG_LEVEL"

These best examples show how shell variables interact with user input and the environment, which is exactly where most real scripts live.


Core examples of variables in shell scripting you’ll use daily

To understand the most useful examples of examples of variables in shell scripting, it helps to split them into a few everyday categories: simple scalars, environment variables, positional parameters, and command substitution.

Simple scalar variables

The most basic example of a variable in shell scripting is a scalar variable that holds a single string or number:

#!/usr/bin/env bash

name="Jordan"
age=29

echo "Name: \(name, Age: \)age"

Notice there are no spaces around the =. That’s one of the classic mistakes beginners make.

You can also do arithmetic using these variables:

#!/usr/bin/env bash

count=5
next=$((count + 1))

echo "Current: \(count, Next: \)next"

These are quiet but powerful examples of variables in shell scripting used for counters, loop indices, and basic math.

Environment variables and configuration

Environment variables are inherited from the parent process and are widely used in Linux, macOS, and WSL setups. Some of the best examples include:

#!/usr/bin/env bash

echo "Home directory: $HOME"
echo "Current user: $USER"
echo "Search path: $PATH"

You can export your own environment variable:

#!/usr/bin/env bash

API_TOKEN="abc123"
export API_TOKEN

./call_api.sh

This pattern is one of the classic examples of variables in shell scripting used for configuration – think database URLs, API keys, or feature flags in CI/CD pipelines.

If you want a deeper reference on environment variables and shells, the GNU Bash manual (hosted by the Free Software Foundation) is a solid technical source: https://www.gnu.org/software/bash/manual/bash.html

Positional parameters: \(1, \)2, and friends

Another favorite example of variables in shell scripting is the set of positional parameters. These represent arguments passed to your script:

#!/usr/bin/env bash

input_file="$1"
output_file="$2"

if [ -z "\(input_file" ] || [ -z "\)output_file" ]; then
  echo "Usage: $0 <input> <output>" >&2
  exit 1
fi

echo "Reading from: $input_file"
echo "Writing to: $output_file"

Here, \(0 is the script name, while \)1 and $2 are positional variables. Real examples include backup scripts, log processors, or wrappers around ffmpeg or curl where arguments control behavior.

The special variables \(# (argument count) and \)@ (all arguments) also show up in many examples of examples of variables in shell scripting:

#!/usr/bin/env bash

echo "You passed $# arguments."
for arg in "$@"; do
  echo "- $arg"
done

Safer quoting: the difference between \(VAR, "\)VAR", and $"VAR"

Many of the best examples of variables in shell scripting are really examples of correct quoting. Misquoting is how you get weird bugs and security problems.

Consider this script that processes a directory that might contain spaces:

#!/usr/bin/env bash

dir="$1"

## Bad: word splitting and glob expansion
cd $dir || exit 1

## Better: preserve spaces and special characters
cd "$dir" || exit 1

The difference between cd \(dir and cd "\)dir" is not cosmetic. Unquoted variables are split on whitespace and subject to globbing. Quoting variables is one of the most practical examples of defensive shell scripting.

A more realistic example:

#!/usr/bin/env bash

backup_dir="/var/backups/$(date +"%Y-%m-%d")"

mkdir -p "$backup_dir"
cp /var/log/syslog "$backup_dir"/

echo "Logs copied to: $backup_dir"

This combines command substitution, quoting, and string concatenation into a single example of a variable in shell scripting that you might actually run in production.


Arrays and loops: modern examples for 2024

As of 2024–2025, most Linux distributions and macOS ship with Bash that supports arrays, which give you more structured examples of variables in shell scripting.

Basic indexed array usage:

#!/usr/bin/env bash

servers=("app1.example.com" "app2.example.com" "db1.example.com")

for host in "${servers[@]}"; do
  echo "Pinging $host ..."
  ping -c 1 "\(host" >/dev/null 2>&1 || echo "Failed: \)host"
done

Here, servers is an array variable, and ${servers[@]} expands to all elements. This is a practical example of iterating over a list of hosts, services, or file paths.

Another 2024-style example: checking multiple Kubernetes contexts or cloud regions from a single script:

#!/usr/bin/env bash

regions=("us-east-1" "us-west-2" "eu-central-1")

for region in "${regions[@]}"; do
  echo "Checking instances in region: $region"
  aws ec2 describe-instances --region "$region" --output text | wc -l
done

These real examples show how arrays help you manage modern multi-region or multi-environment setups without copy‑pasting the same command over and over.

For a more formal introduction to shell programming concepts, the POSIX shell and utilities specification maintained by The Open Group is an authoritative reference: https://pubs.opengroup.org/onlinepubs/9699919799/


Command substitution: using command output as variables

Some of the best examples of variables in shell scripting use command substitution to capture dynamic information.

Classic example: measuring disk usage and warning if it gets too high.

#!/usr/bin/env bash

usage=\((df -h / | awk 'NR==2 {print \)5}' | tr -d '%')

if [ "$usage" -gt 80 ]; then
  echo "Warning: disk usage at ${usage}%" >&2
fi

Here, usage is a variable that holds the numeric percentage. These examples include multiple moving parts: df, awk, tr, and shell comparison.

Another real example of variables in shell scripting with command substitution is capturing a timestamp for logging:

#!/usr/bin/env bash

log_file="/tmp/app-$(date +"%Y%m%d").log"

msg="$1"
now=$(date +"%Y-%m-%d %H:%M:%S")

echo "[\(now] \)msg" >> "$log_file"

This pattern shows up in monitoring scripts, cron jobs, and deployment hooks all the time.


Parameter expansion tricks: defaults, substring, and length

If you want slightly more advanced examples of examples of variables in shell scripting, parameter expansion is where things get interesting.

Default values are everywhere in production scripts:

#!/usr/bin/env bash

LOG_LEVEL="${LOG_LEVEL:-info}"
PORT="${PORT:-8080}"

echo "Starting server on port \(PORT with log level \)LOG_LEVEL"

These examples include the :- syntax, which says “use this default if the variable is unset or empty.”

Substring and length operations are also handy:

#!/usr/bin/env bash

filename="report_2025_Q1.csv"

base=${filename%.csv}   # remove .csv suffix
prefix=${filename%%_*}  # remove from first underscore onward
len=${#filename}        # length of string

echo "Base: $base"
echo "Prefix: $prefix"
echo "Length: $len characters"

These examples of variables in shell scripting are great for quick file‑name manipulation without reaching for Python or Perl.

If you’re learning programming more broadly and want a conceptual grounding in variables and state, introductory computer science materials from universities like MIT OpenCourseWare can help: https://ocw.mit.edu/


Modern scripting patterns: CI/CD, logs, and health checks

Variables show up in almost every modern automation context. Here are a few real examples you’ll see in 2024–2025 DevOps workflows.

CI/CD pipeline environment examples

Imagine a build script running in GitHub Actions or GitLab CI:

#!/usr/bin/env bash

BRANCH_NAME="${GITHUB_REF_NAME:-local}"  # or CI_COMMIT_BRANCH
BUILD_ID="${GITHUB_RUN_ID:-0}"
ARTIFACT_DIR="artifacts/\({BRANCH_NAME}-}\(BUILD_ID}"

mkdir -p "$ARTIFACT_DIR"
cp -r build/* "$ARTIFACT_DIR"/

echo "Artifacts stored in $ARTIFACT_DIR"

These examples of variables in shell scripting show how to combine CI environment variables into meaningful paths and identifiers.

Health check scripts

Simple health checks often rely on variable flags and thresholds:

#!/usr/bin/env bash

URL="${URL:-https://example.com/health}"
TIMEOUT="${TIMEOUT:-5}"

status=\((curl -s -o /dev/null -w "%{http_code}" --max-time "\)TIMEOUT" "$URL")

if [ "$status" -ne 200 ]; then
  echo "Health check failed for \(URL (status: \)status)" >&2
  exit 1
fi

echo "Health check OK for $URL"

This is a practical example of a variable in shell scripting used to parameterize a script without editing the file each time.

Log rotation and retention

Another real example of variables in shell scripting is a simple log cleanup tool:

#!/usr/bin/env bash

LOG_DIR="/var/log/myapp"
DAYS_TO_KEEP="${DAYS_TO_KEEP:-7}"

echo "Removing logs older than \(DAYS_TO_KEEP days from \)LOG_DIR"

find "\(LOG_DIR" -type f -name "*.log" -mtime "+\)DAYS_TO_KEEP" -print -delete

Here, DAYS_TO_KEEP controls retention without touching the script. These are the kinds of examples of variables in shell scripting that keep showing up in sysadmin playbooks.


FAQ: Short answers with clear examples

What are some simple examples of variables in shell scripting?

Some of the simplest examples include scalar assignments like name="Alex", environment variables such as \(HOME or \)PATH, and positional parameters like \(1 and \)2 that hold command‑line arguments. Even count=$((count + 1)) in a loop is a classic example of a variable in shell scripting.

Can you show an example of using user input with a variable?

Yes. A very common example of variables in shell scripting that interact with the user looks like this:

#!/usr/bin/env bash

read -r -p "Enter your name: " name
echo "Hello, $name!"

Here name stores user input typed at the prompt.

How do environment variables differ from normal variables?

Normal shell variables exist only in the current shell. Environment variables are exported with export VAR=value and inherited by child processes. For example, setting export PATH="\(HOME/bin:\)PATH" affects programs you launch afterward. Both kinds appear in real examples of shell scripting, but environment variables are the ones external programs actually see.

What are the best examples of safe variable usage?

The best examples include always quoting variables when they might contain spaces ("\(file" rather than \)file), using parameter expansion for defaults ("${PORT:-8080}"), and avoiding eval. Scripts that handle file names, URLs, and user input without breaking on spaces or special characters are usually following these patterns.

Where can I learn more about shell variable behavior?

For technical details, the Bash reference manual from the GNU project is reliable and up to date: https://www.gnu.org/software/bash/manual/bash.html. For a broader programming foundation, university courses such as those on MIT OpenCourseWare (https://ocw.mit.edu/) explain variables and state in multiple languages, including shell.

Explore More Shell Scripting Snippets

Discover more examples and insights in this category.

View All Shell Scripting Snippets