or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

arguments.mdcommands.mdindex.mdoptions.mdshell.md
tile.json

shell.mddocs/

Shell Utilities

String escaping and unescaping utilities for shell command integration. These utilities help safely construct and parse shell commands by handling special characters and quotes.

Capabilities

String Escaping

Escape strings for safe use in shell commands by adding quotes and escaping special characters.

/**
 * Escape string for safe shell command usage
 * @param w String to escape
 * @returns Escaped string safe for shell execution
 */
function escape(w: string): string;

Usage Examples:

const { shell } = require('coa');

// Basic escaping
const safe1 = shell.escape('hello world');
console.log(safe1); // "hello world"

// Escaping special characters
const safe2 = shell.escape('file with $pecial char$');
console.log(safe2); // "file with \$pecial char\$"

// No escaping needed for simple strings
const safe3 = shell.escape('simple');
console.log(safe3); // simple

// Escaping quotes and backslashes
const safe4 = shell.escape('say "hello" and \\escape');
console.log(safe4); // "say \"hello\" and \\\\escape"

String Unescaping

Unescape shell-escaped strings to restore original values.

/**
 * Unescape shell-escaped string
 * @param w Escaped string to unescape
 * @returns Original unescaped string
 */
function unescape(w: string): string;

Usage Examples:

const { shell } = require('coa');

// Basic unescaping
const original1 = shell.unescape('"hello world"');
console.log(original1); // hello world

// Unescaping special characters
const original2 = shell.unescape('file\\ with\\ spaces');
console.log(original2); // file with spaces

// Unescaping quotes
const original3 = shell.unescape('"say \\"hello\\""');
console.log(original3); // say "hello"

// Unescaping backslashes
const original4 = shell.unescape('path\\\\to\\\\file');
console.log(original4); // path\to\file

Module Access

The shell utilities are available through multiple access patterns.

// Main export pattern
const { shell } = require('coa');
shell.escape(str);
shell.unescape(str);

// Direct import of shell module
const shell = require('coa/lib/shell');
shell.escape(str);
shell.unescape(str);

Usage Examples:

// From main COA module
const COA = require('coa');
const escaped = COA.shell.escape('my string');

// Destructured import
const { shell } = require('coa');
const escaped = shell.escape('my string');
const unescaped = shell.unescape(escaped);

// Direct shell module import
const shell = require('coa/lib/shell');
const escaped = shell.escape('my string');

Practical Use Cases

Common scenarios where shell utilities are useful.

Command Construction:

const { shell } = require('coa');
const { exec } = require('child_process');

function runCommand(program, args, options = {}) {
    // Safely escape all arguments
    const escapedArgs = args.map(shell.escape);
    const command = `${program} ${escapedArgs.join(' ')}`;
    
    console.log('Executing:', command);
    return new Promise((resolve, reject) => {
        exec(command, options, (error, stdout, stderr) => {
            if (error) reject(error);
            else resolve({ stdout, stderr });
        });
    });
}

// Usage
runCommand('grep', ['search term', 'file with spaces.txt'])
    .then(result => console.log(result.stdout));

Completion System Integration:

const { shell } = require('coa');

// Used internally by COA's completion system
function processCompletionArgs(rawArgs) {
    return rawArgs.map(shell.unescape);
}

function formatCompletionResults(results) {
    return results.map(shell.escape).join('\n');
}

Configuration File Processing:

const { shell } = require('coa');

function parseShellConfig(configLine) {
    // Split on spaces but respect quoted strings
    const parts = [];
    let current = '';
    let inQuotes = false;
    
    for (let i = 0; i < configLine.length; i++) {
        const char = configLine[i];
        if (char === '"' && configLine[i-1] !== '\\') {
            inQuotes = !inQuotes;
            current += char;
        } else if (char === ' ' && !inQuotes) {
            if (current) {
                parts.push(shell.unescape(current));
                current = '';
            }
        } else {
            current += char;
        }
    }
    
    if (current) {
        parts.push(shell.unescape(current));
    }
    
    return parts;
}

// Usage
const config = 'program --option "value with spaces" --flag';
const parsed = parseShellConfig(config);
console.log(parsed);
// ['program', '--option', 'value with spaces', '--flag']

Implementation Details

The shell utilities handle various escaping scenarios:

Character Escaping Rules:

  • Escapes: ", ', $, `, \
  • Adds double quotes around strings containing spaces
  • Preserves existing quotes appropriately
  • Handles nested escaping correctly

Usage Examples:

const { shell } = require('coa');

// Test various escaping scenarios
const testCases = [
    'simple',                    // No escaping needed
    'with spaces',              // Adds quotes
    'with"quotes',              // Escapes quotes
    "with'single'quotes",       // Escapes single quotes
    'with$variables',           // Escapes dollar signs
    'with`backticks`',          // Escapes backticks
    'with\\backslashes',        // Escapes backslashes
    'complex "mixed" $case',    // Multiple escaping
];

testCases.forEach(test => {
    const escaped = shell.escape(test);
    const unescaped = shell.unescape(escaped);
    console.log(`Original: ${test}`);
    console.log(`Escaped:  ${escaped}`);
    console.log(`Restored: ${unescaped}`);
    console.log(`Match:    ${test === unescaped}`);
    console.log('---');
});

Integration with COA Commands

Shell utilities are used internally by COA for completion and argument processing.

Usage Examples:

const COA = require('coa');

const cmd = COA.Cmd()
    .name('deploy')
    .completable()  // Uses shell utilities internally
    .opt()
        .name('env')
        .comp(function(opts) {
            // Completion results are automatically escaped
            return ['production', 'staging', 'development'];
        })
        .end()
    .act(function(opts, args) {
        // Arguments are automatically unescaped
        console.log('Environment:', opts.env);
    });

// The completion system handles escaping/unescaping automatically
// User types: deploy --env prod[TAB]
// System suggests: production (properly escaped)