Back to roadmaps shell-script Course

Variables and Command-Line Arguments in Bash

Variables allow your scripts to store and reuse values dynamically. Arguments let users pass custom inputs at runtime.


1. Defining and Using Variables

Assign variables without spaces around the = sign:

#!/bin/bash
# Define variables
APP_NAME="MyWebApp"
VERSION="1.0.3"

# Use variables by prefixing with $
echo "Deploying $APP_NAME version $VERSION"

2. Reading Command-Line Arguments

When you run a script with arguments, they are available via positional variables:

#!/bin/bash
# Usage: ./deploy.sh production v1.2.0

ENVIRONMENT=$1  # First argument
VERSION=$2      # Second argument

echo "Deploying to: $ENVIRONMENT"
echo "Version: $VERSION"

Special Argument Variables

Variable Meaning
$0 The script filename itself
$1, $2, $3 Positional arguments (1st, 2nd, 3rd)
$# Total number of arguments passed
$@ All arguments as a list
$? Exit code of the last command run

3. Capturing Command Output

Assign the output of a command to a variable using $():

#!/bin/bash
# Capture current date and git commit hash
CURRENT_DATE=$(date +%Y-%m-%d)
LATEST_COMMIT=$(git rev-parse --short HEAD)

echo "Deploy timestamp: $CURRENT_DATE"
echo "Git commit: $LATEST_COMMIT"
Published on Last updated: