Skip to main content

Snippets - Command Templates

Snippets allow you to save frequently used commands, scripts, and code blocks for quick reuse. With variable substitution, you can create dynamic templates that adapt to different situations.

What are Snippets?

Simple Explanation: Think of snippets as your personal command library. Instead of typing the same long commands repeatedly or searching through your bash history, save them once and execute with a single click.

Example:

# Without Snippets - Type this every time:
rsync -avz --progress /local/path/ user@server:/remote/path/

# With Snippets - Click and run!
# Save once, use forever

Why Use Snippets?

⏱️ Time Saving

Before Snippets:

1. Remember command syntax
2. Type entire command
3. Fix typos
4. Repeat for each use
Total: 2-5 minutes per command

With Snippets:

1. Click snippet name
2. Fill variables (if any)
3. Execute
Total: 10 seconds

Save 80-90% of your time!

✅ Accuracy

  • No typos in saved commands
  • Correct syntax preserved
  • Options saved correctly
  • Paths remembered

📚 Knowledge Base

  • Document what commands do
  • Add descriptions and notes
  • Organize by category
  • Share with team

🎯 Consistency

  • Same command structure every time
  • Standard naming conventions
  • Consistent options
  • Repeatable processes

Key Features

1. Variable Substitution

Create dynamic templates with {{variable}} syntax:

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

# When executing:
container_name: my-app
command: /bin/bash

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

Powerful & Flexible!

2. Categories

Organize snippets by purpose:

📁 Docker Commands
- Start Container
- Stop Container
- View Logs

📁 Database Operations
- Backup MySQL
- Restore PostgreSQL
- Export MongoDB

📁 File Operations
- Compress Files
- Extract Archives
- Sync Directories

Find snippets instantly:

  • Search by name
  • Search by command content
  • Filter by category
  • Sort by use count

4. Usage Statistics

Track your most-used commands:

Top Snippets:
1. Docker Restart (47 uses)
2. Git Pull & Rebase (35 uses)
3. npm Build Production (28 uses)

Identify your workflow patterns!

5. Quick Execution

Multiple ways to run:

  • Click execute button
  • Keyboard shortcuts
  • From terminal tab
  • Batch execution

6. Templates Library

Pre-made snippets for common tasks:

  • Docker commands
  • Git operations
  • System administration
  • Database management
  • Web development

Start productive immediately!

Common Use Cases

1. Docker Management

# Start Services
docker-compose up -d {{service_name}}

# View Logs
docker logs -f --tail={{lines}} {{container}}

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

# Cleanup
docker system prune -a --volumes

2. Git Operations

# Branch Management
git checkout -b {{branch_name}}
git push -u origin {{branch_name}}

# Syncing
git fetch origin && git rebase origin/{{branch}}

# Cleanup
git branch --merged | grep -v "\*" | xargs -n 1 git branch -d

3. File Operations

# Backup with Timestamp
tar -czf {{name}}_$(date +%Y%m%d_%H%M%S).tar.gz {{directory}}

# Find Large Files
find {{path}} -type f -size +{{size}}M -exec ls -lh {} \;

# Secure Copy
rsync -avz --progress {{source}} {{user}}@{{host}}:{{destination}}

4. Database Operations

# MySQL Backup
mysqldump -u {{user}} -p{{password}} {{database}} > backup_$(date +%Y%m%d).sql

# PostgreSQL Restore
psql -U {{user}} -d {{database}} < {{backup_file}}

# MongoDB Export
mongoexport --db={{database}} --collection={{collection}} --out={{file}}

5. System Administration

# Disk Usage Analysis
du -sh {{directory}}/* | sort -h

# Process Management
ps aux | grep {{process_name}}
kill -9 $(pgrep -f {{process_name}})

# Network Testing
ping -c {{count}} {{host}}
curl -I {{url}}

6. Web Development

# Node.js
npm install && npm run {{script}}
pm2 restart {{app}} --update-env

# Python
python -m venv {{env_name}}
source {{env_name}}/bin/activate
pip install -r requirements.txt

# Build & Deploy
npm run build
rsync -avz build/ {{user}}@{{server}}:{{path}}

Snippet Components

Name

Clear, descriptive identifier:

✓ "Docker: Restart Container"
✓ "Git: Create Feature Branch"
✓ "Database: MySQL Backup"

✗ "Command 1"
✗ "docker"
✗ "script"

Command/Script

The actual command(s) to execute:

# Single command
docker restart {{container_name}}

# Multiple commands
cd {{project_path}}
git pull origin {{branch}}
npm install
npm run build

Variables

Dynamic placeholders:

{{container_name}}
{{project_path}}
{{branch}}
{{environment}}

Category

Organization bucket:

- Development
- Production
- Backup
- Maintenance

Description

What it does and when to use:

Restarts a specific Docker container by name.
Use when container needs a clean restart after
configuration changes.

How It Works

Creating a Snippet

1. Click "New Snippet"
2. Enter name: "Docker Restart"
3. Add command: docker restart {{container}}
4. Add description
5. Choose category
6. Save

Variables auto-detected from {{}} syntax!

Executing a Snippet

1. Find snippet in list
2. Click "Execute"
3. Fill in variables (if any)
4. Confirm and run

Or use keyboard shortcuts for faster execution!

Organizing Snippets

1. Create categories
2. Assign snippets to categories
3. Use search to find
4. Sort by name or usage

Real-World Examples

Example 1: Development Workflow

Scenario: Deploy to staging server

Snippet:

# Name: Deploy to Staging
# Category: Deployment

cd {{project_path}}
git checkout {{branch}}
git pull origin {{branch}}
npm install
npm run build:staging
rsync -avz --delete build/ {{user}}@staging.example.com:/var/www/app/
ssh {{user}}@staging.example.com "pm2 restart {{app_name}}"

Usage:

Variables:
project_path: /Users/dev/myapp
branch: develop
user: deployer
app_name: myapp-staging

Execute → Done in 30 seconds!

Example 2: Database Maintenance

Scenario: Daily backup routine

Snippet:

# Name: MySQL Backup All Databases
# Category: Database

BACKUP_DIR="/backups/mysql"
DATE=$(date +%Y%m%d_%H%M%S)

mkdir -p $BACKUP_DIR

# Backup all databases
mysqldump -u {{user}} -p{{password}} \
--all-databases \
--single-transaction \
--quick \
--lock-tables=false \
> $BACKUP_DIR/all_databases_$DATE.sql

# Compress
gzip $BACKUP_DIR/all_databases_$DATE.sql

# Delete backups older than 7 days
find $BACKUP_DIR -name "*.sql.gz" -mtime +7 -delete

echo "Backup completed: all_databases_$DATE.sql.gz"

Run daily with one click!

Example 3: Docker Stack Management

Scenario: Manage microservices

Snippets Collection:

# 1. Start All Services
docker-compose -f {{compose_file}} up -d

# 2. View Service Logs
docker-compose -f {{compose_file}} logs -f {{service}}

# 3. Restart Service
docker-compose -f {{compose_file}} restart {{service}}

# 4. Scale Service
docker-compose -f {{compose_file}} up -d --scale {{service}}={{count}}

# 5. Stop All Services
docker-compose -f {{compose_file}} down

Complete stack management in snippets!

Example 4: Server Health Check

Snippet:

# Name: Server Health Check
# Category: Monitoring

echo "=== Server Health Check ==="
echo ""

echo "CPU Usage:"
top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1"%"}'

echo ""
echo "Memory Usage:"
free -h | grep "Mem:" | awk '{print $3 "/" $2 " (" $3/$2*100 "%)"}'

echo ""
echo "Disk Usage:"
df -h | grep "^/dev/"

echo ""
echo "Top Processes:"
ps aux --sort=-%cpu | head -6

echo ""
echo "Docker Containers:"
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"

echo ""
echo "Last 10 System Errors:"
journalctl -p err -n 10 --no-pager

Comprehensive health check in one snippet!

Integration Features

Terminal Integration

Execute snippets directly in terminal:

1. Open terminal tab
2. Click snippet icon
3. Select snippet
4. Variables filled
5. Command inserted
6. Press Enter to run

SFTP Integration

Run snippets on SFTP servers:

1. Browse files in SFTP
2. Right-click file/folder
3. "Run Snippet"
4. Variables auto-filled with paths
5. Execute

Host Groups

Apply snippets to multiple hosts:

1. Select snippet
2. Choose "Execute on Group"
3. Select host group
4. Run on all simultaneously

Best Practices

1. Naming Convention

Use clear, hierarchical names:

✓ Docker: Container Restart
✓ Git: Feature Branch Create
✓ Database: MySQL Full Backup
✓ Server: Health Check Complete

Pattern: [Category]: [Action] [Object]

2. Add Descriptions

Document what, when, and why:

Name: Database: PostgreSQL Vacuum
Description: Reclaim storage and optimize database.
Run weekly or after large DELETE operations.
Safe to run during low-traffic periods.

3. Use Variables Wisely

✓ {{database_name}}  - Clear purpose
✓ {{backup_file}} - Descriptive
✓ {{environment}} - Meaningful

✗ {{var1}} - Unclear
✗ {{x}} - Too short
✗ {{database_name_for_backup_operation}} - Too long

4. Organize with Categories

Create logical groupings:

📁 Daily Operations
📁 Emergency Procedures
📁 Deployment
📁 Monitoring
📁 Maintenance

5. Test Before Saving

1. Test command manually
2. Verify it works correctly
3. Then save as snippet
4. Test snippet execution
5. Update description if needed

6. Add Error Handling

# Good: With error handling
if [ -d "{{directory}}" ]; then
cd {{directory}}
git pull origin {{branch}}
else
echo "Directory not found!"
exit 1
fi

# Better: With notifications
if [ $? -eq 0 ]; then
echo "✓ Success!"
else
echo "✗ Failed!"
exit 1
fi

7. Use Comments

# Backup database
mysqldump -u {{user}} -p{{password}} {{db}} > backup.sql

# Compress backup (saves 80% space)
gzip backup.sql

# Upload to remote server
scp backup.sql.gz {{user}}@{{backup_server}}:/backups/

# Cleanup local file
rm backup.sql.gz

Security Considerations

⚠️ Never Store Passwords

Bad:

# DON'T DO THIS!
mysql -u root -pMyPassword123 mydb

Good:

# Use variables for credentials
mysql -u {{user}} -p{{password}} {{database}}

# Or better: Use credential files
mysql --defaults-file=~/.my.cnf {{database}}

🔒 Sensitive Commands

Mark snippets containing:

  • Password changes
  • Permission modifications
  • Data deletion
  • Production deployments

Add warnings in description:

⚠️ DANGER: This deletes production data!
⚠️ Requires sudo privileges
⚠️ Production only - verify environment first

🎯 Scope Limitations

# Good: Limited scope
docker restart {{container_name}}

# Dangerous: Wide scope
docker stop $(docker ps -aq) # Stops ALL containers!
docker system prune -a --force # Deletes everything!

Add confirmation prompts:

echo "This will delete ALL Docker volumes!"
read -p "Are you sure? (yes/no) " confirm
if [ "$confirm" != "yes" ]; then exit 1; fi

Tips & Tricks

1. Chaining Snippets

Execute multiple snippets in sequence:

Snippet 1: Stop Application
Snippet 2: Backup Database
Snippet 3: Deploy New Version
Snippet 4: Start Application
Snippet 5: Health Check

2. Default Variables

Set common defaults:

{{user}} = deployer (common default)
{{environment}} = staging (safe default)
{{branch}} = develop (development branch)

3. Snippet Shortcuts

Assign keyboard shortcuts:

Ctrl+Shift+1 = Most used snippet
Ctrl+Shift+2 = Second most used
Ctrl+Shift+3 = Third most used

4. Template Exports

Share with team:

1. Export category as template
2. Share .json file
3. Team imports
4. Everyone uses same commands

5. Version Control

Track snippet changes:

Name: Deploy v2.0
Description: Updated for new infrastructure (2024-01-15)
Previous version in: Deploy v1.0 (archived)

Comparison with Alternatives

vs Bash History

Bash History:

✗ No organization
✗ No descriptions
✗ Hard to find
✗ No variables
✓ Automatic

Snippets:

✓ Organized categories
✓ Clear descriptions
✓ Quick search
✓ Variable support
✗ Manual save

vs Bash Aliases

Bash Aliases:

✓ Very quick access
✗ Local to shell
✗ No variables
✗ No descriptions
✗ Syntax limitations

Snippets:

✓ Available everywhere in Xermius
✓ Variable substitution
✓ Full descriptions
✓ Visual interface
✗ Requires app

vs Shell Scripts

Shell Scripts:

✓ Full programming
✓ Complex logic
✓ Version control
✗ Separate files
✗ Path management

Snippets:

✓ Integrated in app
✓ Visual management
✓ Quick access
✗ Limited complexity
✗ Less programming features

Best Approach: Use all three!

  • Aliases: Very frequent, simple commands
  • Snippets: Medium complexity, GUI management
  • Scripts: Complex logic, version-controlled

Next Steps