Skip to main content

Variables in Snippets

Variables transform static commands into flexible, reusable templates. Learn how to use {{variable}} syntax to create powerful dynamic snippets.

What are Variables?

Simple Explanation: Variables are placeholders in your commands that get replaced with actual values when you execute the snippet.

Example:

# Template with variables
docker exec -it {{container_name}} {{command}}

# When executing, you provide:
container_name = my-app
command = /bin/bash

# Results in:
docker exec -it my-app /bin/bash

Same snippet, infinite variations!

Why Use Variables?

1. Flexibility

One snippet, many uses:

# Single template
git checkout -b {{branch_name}}

# Can create:
git checkout -b feature/user-auth
git checkout -b bugfix/login-error
git checkout -b hotfix/security-patch

2. Reusability

Don't repeat yourself:

# Without variables - Need 3 snippets:
docker restart my-app
docker restart api-service
docker restart worker

# With variables - 1 snippet:
docker restart {{container}}

3. Safety

Avoid typos and mistakes:

# Easy to mistype manually:
scp file.txt user@192.168.1.100:/home/user/path/

# With variables - fill in form:
{{file}} = file.txt
{{host}} = 192.168.1.100
{{path}} = /home/user/path

# Executed correctly every time!

4. Documentation

Self-documenting commands:

# Clear what needs to be provided:
mysqldump -u {{username}} -p{{password}} {{database}} > {{backup_file}}

# vs cryptic:
mysqldump -u USER -p PASSWORD DB > FILE

Variable Syntax

Basic Syntax

Use double curly braces:

{{variable_name}}

Rules:

  • Must start with letter or underscore
  • Can contain letters, numbers, underscores
  • Case-sensitive
  • No spaces

Valid:

✓ {{username}}
✓ {{user_name}}
✓ {{userName}}
✓ {{_temp}}
✓ {{port1}}

Invalid:

✗ {username}        # Single braces
✗ {{user name}} # Space in name
✗ {{user-name}} # Hyphen not allowed
✗ {{1user}} # Starts with number
✗ {{ username }} # Spaces around name

Multiple Variables

Use as many as needed:

scp {{local_file}} {{user}}@{{host}}:{{remote_path}}

# 4 variables:
# - local_file
# - user
# - host
# - remote_path

Repeated Variables

Same variable used multiple times:

docker cp {{container}}:/app/logs/{{file}} ./{{file}}

# Prompts once for:
# - container
# - file

# Then uses {{file}} twice

Value used consistently!

Auto-Detection

Variables are automatically detected when you create/edit snippets.

Example:

┌──────────────────────────────────────────┐
│ New Snippet │
├──────────────────────────────────────────┤
│ Command: │
│ ┌──────────────────────────────────────┐ │
│ │ rsync -avz {{source}} \ │ │
│ │ {{user}}@{{host}}:{{destination}} │ │
│ └──────────────────────────────────────┘ │
│ │
│ ✓ Variables detected: │
│ • source │
│ • user │
│ • host │
│ • destination │
│ │
│ [Cancel] [Create] │
└──────────────────────────────────────────┘

No manual configuration needed!

Executing Snippets with Variables

Variable Input Dialog

When executing snippet with variables:

┌──────────────────────────────────────────┐
│ Execute Snippet: Sync Files │
├──────────────────────────────────────────┤
│ Fill in the variables below: │
│ │
│ Source Path: * │
│ [/local/project/build ] │
│ │
│ User: * │
│ [deployer ] │
│ │
│ Host: * │
│ [staging.example.com ] │
│ │
│ Destination: * │
│ [/var/www/app ] │
│ │
│ Preview: │
│ rsync -avz /local/project/build \ │
│ deployer@staging.example.com:/var/www/app│
│ │
│ [Cancel] [Execute] │
└──────────────────────────────────────────┘

Live Preview: See command before executing!

Default Values

Provide sensible defaults:

In Description:

Description:
Deploys application to server

Common values:
- user: deployer
- host: staging.example.com
- path: /var/www/app

Or in variable name:

# Suggestive naming
{{username_or_deployer}}
{{host_staging_or_production}}
{{port_default_22}}

Required vs Optional

All variables are required by default.

Make optional with conditional logic:

#!/bin/bash

# Optional port (defaults to 22)
PORT=${1:-22}
ssh -p $PORT {{user}}@{{host}}

Or handle in command:

docker logs {{container}} ${FOLLOW:+--follow} ${TAIL:+-n $TAIL}

Variable Naming Best Practices

1. Be Descriptive

Good:

✓ {{database_name}}
✓ {{backup_directory}}
✓ {{remote_server_ip}}
✓ {{git_branch_name}}

Bad:

✗ {{db}}
✗ {{dir}}
✗ {{ip}}
✗ {{b}}

2. Use Consistent Naming

Pick a style and stick to it:

snake_case (Recommended):

{{database_name}}
{{user_name}}
{{backup_file}}

camelCase:

{{databaseName}}
{{userName}}
{{backupFile}}

Don't mix:

✗ {{database_name}} and {{userName}}  # Inconsistent!

3. Be Specific

Vague:

{{file}}          # Which file?
{{name}} # Name of what?
{{path}} # Path to what?

Specific:

{{config_file}}
{{container_name}}
{{backup_path}}

Use prefixes:

# Database group
{{db_host}}
{{db_port}}
{{db_name}}
{{db_user}}
{{db_password}}

# Server group
{{server_host}}
{{server_port}}
{{server_user}}

5. Indicate Type/Format

Add hints in name:

{{port_number}}        # Expects number
{{email_address}} # Expects email format
{{url_endpoint}} # Expects URL
{{file_path}} # Expects path
{{iso_date}} # Expects YYYY-MM-DD

Common Variable Patterns

1. Connection Variables

# SSH Connection
ssh {{user}}@{{host}} -p {{port}}

# Database Connection
mysql -h {{host}} -P {{port}} -u {{user}} -p{{password}} {{database}}

# Redis Connection
redis-cli -h {{host}} -p {{port}} -a {{password}}

2. File Operation Variables

# Copy
cp {{source_file}} {{destination_file}}

# Move
mv {{from_path}} {{to_path}}

# Archive
tar -czf {{archive_name}}.tar.gz {{directory}}

# Extract
unzip {{zip_file}} -d {{extract_to}}

3. Docker Variables

# Container Operations
docker {{action}} {{container_name}}

# Execute Command
docker exec -it {{container}} {{command}}

# Port Mapping
docker run -p {{host_port}}:{{container_port}} {{image}}

# Volume Mount
docker run -v {{host_path}}:{{container_path}} {{image}}

4. Git Variables

# Branch Operations
git checkout -b {{branch_name}}
git push origin {{branch_name}}

# Remote Operations
git remote add {{remote_name}} {{remote_url}}

# Commit
git commit -m "{{commit_message}}"

5. Deployment Variables

# Deploy
rsync -avz {{local_path}}/ \
{{user}}@{{host}}:{{remote_path}}

# Restart Service
ssh {{user}}@{{host}} "systemctl restart {{service_name}}"

# Environment
export {{env_var}}={{value}}

Advanced Variable Techniques

1. Variable Substitution in Paths

# User-specific paths
/home/{{username}}/{{project}}/{{file}}

# Date-based paths
/backups/{{year}}/{{month}}/{{day}}/{{filename}}

# Environment paths
/var/www/{{environment}}/{{application}}/

2. Command Building

# Conditional flags
docker run {{image}} {{flags}} {{command}}

# Where {{flags}} could be:
# -d --restart=always
# -it --rm
# --network=host

3. Multi-Line Variables

# SQL Query
mysql -e "{{query}}" {{database}}

# Where {{query}} is:
SELECT *
FROM users
WHERE status = 'active'
LIMIT 100

4. Variable in Variable

Not supported directly, but can use bash:

#!/bin/bash

# Base variable
BASE_PATH="/var/www/{{environment}}"

# Derived path
DEPLOY_PATH="$BASE_PATH/{{application}}/current"

echo "Deploying to: $DEPLOY_PATH"

5. Array-like Variables

# Multiple values
for server in {{server1}} {{server2}} {{server3}}; do
ssh $server "{{command}}"
done

Or better:

# Server list in one variable
for server in {{server_list}}; do
ssh $server "{{command}}"
done

# Where {{server_list}} = "web1 web2 web3"

Variable Validation

Manual Validation in Command

#!/bin/bash

# Check if port is number
if ! [[ "{{port}}" =~ ^[0-9]+$ ]]; then
echo "Error: Port must be a number"
exit 1
fi

# Check if directory exists
if [ ! -d "{{directory}}" ]; then
echo "Error: Directory does not exist"
exit 1
fi

# Check if email format
if ! [[ "{{email}}" =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}$ ]]; then
echo "Error: Invalid email format"
exit 1
fi

# Proceed with command...

Input Sanitization

#!/bin/bash

# Remove dangerous characters
SAFE_INPUT=$(echo "{{user_input}}" | tr -d ';|&$')

# Use sanitized input
echo "Processing: $SAFE_INPUT"

Confirmation Prompts

#!/bin/bash

echo "About to execute on: {{environment}}"
echo "Command: {{command}}"
read -p "Continue? (yes/no): " confirm

if [ "$confirm" != "yes" ]; then
echo "Cancelled"
exit 0
fi

# Execute...

Real-World Examples

Example 1: Database Backup

#!/bin/bash

# Variables
BACKUP_DIR="/backups/mysql"
DATE=$(date +%Y%m%d_%H%M%S)
FILENAME="{{database}}_${DATE}.sql"

# Create backup directory
mkdir -p $BACKUP_DIR

# Dump database
echo "Backing up {{database}}..."
mysqldump -h {{host}} \
-u {{user}} \
-p{{password}} \
{{database}} \
> $BACKUP_DIR/$FILENAME

# Compress
echo "Compressing..."
gzip $BACKUP_DIR/$FILENAME

# Verify
if [ -f "$BACKUP_DIR/$FILENAME.gz" ]; then
SIZE=$(du -h "$BACKUP_DIR/$FILENAME.gz" | cut -f1)
echo "✓ Backup complete: $FILENAME.gz ($SIZE)"
else
echo "✗ Backup failed!"
exit 1
fi

# Cleanup old backups (keep last 7 days)
find $BACKUP_DIR -name "{{database}}_*.sql.gz" -mtime +7 -delete
echo "✓ Old backups cleaned up"

Variables:

  • {{host}} - Database host
  • {{user}} - Database user
  • {{password}} - Database password
  • {{database}} - Database name

Example 2: Multi-Server Deployment

#!/bin/bash

# Servers array
SERVERS="{{server_list}}"

# Function to deploy to one server
deploy_to_server() {
local server=$1
echo "Deploying to $server..."

# Sync files
rsync -avz --delete \
{{local_path}}/ \
{{user}}@$server:{{remote_path}}/

# Restart service
ssh {{user}}@$server "systemctl restart {{service}}"

# Health check
if curl -f http://$server/health > /dev/null 2>&1; then
echo "✓ $server deployed successfully"
else
echo "✗ $server health check failed"
return 1
fi
}

# Deploy to each server
for server in $SERVERS; do
deploy_to_server $server || exit 1
done

echo "✓ All servers deployed successfully"

Variables:

  • {{server_list}} - Space-separated server IPs (e.g., "10.0.1.1 10.0.1.2")
  • {{local_path}} - Local build directory
  • {{remote_path}} - Remote deployment directory
  • {{user}} - SSH user
  • {{service}} - Systemd service name

Example 3: Docker Stack Management

#!/bin/bash

STACK_NAME="{{stack_name}}"
ENVIRONMENT="{{environment}}"
COMPOSE_FILE="docker-compose.{{environment}}.yml"

# Function to check service health
check_health() {
local service=$1
local retries=30

echo "Checking $service health..."
while [ $retries -gt 0 ]; do
if docker ps | grep "${STACK_NAME}_${service}" | grep -q "healthy\|Up"; then
echo "✓ $service is healthy"
return 0
fi

echo "Waiting for $service... ($retries retries left)"
sleep 2
retries=$((retries-1))
done

echo "✗ $service failed to become healthy"
return 1
}

# Stop existing stack
echo "Stopping existing stack..."
docker-compose -f $COMPOSE_FILE -p $STACK_NAME down

# Pull latest images
echo "Pulling latest images..."
docker-compose -f $COMPOSE_FILE pull

# Start stack
echo "Starting stack..."
docker-compose -f $COMPOSE_FILE -p $STACK_NAME up -d

# Check health of each service
for service in {{services}}; do
check_health $service || exit 1
done

echo "✓ Stack deployed successfully"
docker-compose -f $COMPOSE_FILE ps

Variables:

  • {{stack_name}} - Docker stack name
  • {{environment}} - Environment (dev, staging, prod)
  • {{services}} - Space-separated service names

Example 4: Certificate Management

#!/bin/bash

DOMAIN="{{domain}}"
EMAIL="{{email}}"
WEBROOT="{{webroot_path}}"

# Check if certificate exists
if [ -f "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" ]; then
# Renew existing certificate
echo "Renewing certificate for $DOMAIN..."
certbot renew --quiet

# Check expiry
EXPIRY=$(openssl x509 -enddate -noout -in /etc/letsencrypt/live/$DOMAIN/fullchain.pem | cut -d= -f2)
echo "Certificate valid until: $EXPIRY"
else
# Obtain new certificate
echo "Obtaining new certificate for $DOMAIN..."
certbot certonly \
--webroot \
--webroot-path $WEBROOT \
--email $EMAIL \
--agree-tos \
--no-eff-email \
-d $DOMAIN \
-d www.$DOMAIN
fi

# Reload nginx
echo "Reloading nginx..."
nginx -t && systemctl reload nginx

echo "✓ Certificate management complete"

Variables:

  • {{domain}} - Domain name
  • {{email}} - Contact email
  • {{webroot_path}} - Web root path

Troubleshooting Variables

Variable Not Replaced

Issue: Variable appears as-is in output

Causes:

  • Wrong syntax (single braces, spaces)
  • Variable name mismatch
  • Snippet not saved properly

Fix:

# Check syntax
✗ {variable}
✓ {{variable}}

# Check name matches exactly
Command: {{container_name}}
Prompt: container_name ✓

Command: {{container_name}}
Prompt: containerName ✗ (case mismatch!)

Missing Variable Prompt

Issue: Variable not prompted during execution

Causes:

  • Syntax error in snippet
  • Variable detection failed
  • Cache issue

Fix:

  1. Edit snippet
  2. Check variable syntax
  3. Save snippet
  4. Try executing again

Wrong Variable Value

Issue: Variable replaced with wrong value

Causes:

  • Copy/paste error
  • Similar variable names
  • Repeating variable confusion

Fix:

  • Use distinct variable names
  • Double-check values before executing
  • Use preview feature

Special Characters in Variables

Issue: Variable value breaks command

Example:

# Variable value: my file.txt (has space)
# Command breaks:
cp {{file}} backup/
# Results in:
cp my file.txt backup/ # Interpreted as 3 arguments!

Fix:

# Quote variables with potential spaces
cp "{{file}}" backup/

# Or in snippet description:
"Note: Enclose value in quotes if it contains spaces"

Tips & Best Practices

1. Document Variable Requirements

In description:

Variables:
- database: MySQL database name (e.g., myapp_production)
- host: Server IP or hostname (e.g., 192.168.1.100)
- user: MySQL username with backup privileges
- password: User's password (stored securely)

2. Provide Examples

Example values:
database: myapp_production
host: db1.example.com
user: backup_user
password: ********

3. Use Variable Groups

Related variables together:

# Source
{{source_host}}
{{source_user}}
{{source_path}}

# Destination
{{dest_host}}
{{dest_user}}
{{dest_path}}

4. Avoid Too Many Variables

Too many:

# 15 variables - too complex!
docker run \
-e {{var1}}={{val1}} \
-e {{var2}}={{val2}} \
... # 13 more
{{image}}

Better:

# Use config file
docker run --env-file {{config_file}} {{image}}

5. Consider Default Values

In bash:

# Use provided value or default
HOST=${HOST:-{{host}}}
PORT=${PORT:-22}

6. Test with Sample Values

1. Create snippet
2. Execute with test values
3. Verify output
4. Document working values
5. Use for real

Next Steps