Skip to content

Parsear argumentos de línea de comandos snippet

Lee lo que el usuario tecleó después del nombre de tu programa.

Lee lo que el usuario tecleó después del nombre de tu programa. El array crudo siempre está a un paso — argv en la herencia de C, ARGV en Ruby, process.argv en Node — pero cada runtime lo desplaza de forma distinta (Node oculta el runtime y la ruta del script en las posiciones 0 y 1), y parsear flags a mano se vuelve feo rápido. Recurre al parser incluido en cuanto tengas flags con valores: flag en Go, argparse en Python.

Receta ejecutable · 10 lenguajes
System & CLIcliargvflags

Every language

10 lenguajes, copy-ready. One at a time with syntax highlighting, or all inline.

JSJavaScript
// greet.js — node greet.js --name Ada
const args = process.argv.slice(2);
const i = args.indexOf('--name');
const name = i !== -1 ? args[i + 1] : 'world';
console.log(`Hello, ${name}!`);

argv[0] is the node binary and argv[1] the script — slice(2) is the user's part.

TSTypeScript
const args: string[] = process.argv.slice(2);
const name = args.find((_, i) => args[i - 1] === '--name') ?? 'world';
console.log(`Hello, ${name}!`);

Same slice(2) offset as Node. For real flag parsing use util.parseArgs (built in since Node 18.3).

GoGo
package main

import "flag"

func main() {
	name := flag.String("name", "world", "who to greet")
	flag.Parse()
	println("Hello, " + *name + "!")
}

The stdlib flag package handles --name Ada and --name=Ada. Positional args follow flag.Args().

RsRust
fn main() {
    let name = std::env::args()
        .skip(1)
        .find(|a| !a.starts_with('-'))
        .unwrap_or_else(|| "world".into());
    println!("Hello, {name}!");
}

args() panics on non-UTF8; args_os() keeps raw OsStrings. clap is the crate for real CLIs.

PHPPHP
<?php
// greet.php — php greet.php Ada
$name = $argv[1] ?? 'world';
echo "Hello, $name!", PHP_EOL;

$argv[0] is the script name. Use getopt() for flags: getopt('', ['name:'])['name'].

PyPython
import argparse

parser = argparse.ArgumentParser(description='Greet someone.')
parser.add_argument('--name', default='world', help='who to greet')
args = parser.parse_args()
print(f'Hello, {args.name}!')

argparse builds --help for free and exits non-zero on bad input.

CC
#include <stdio.h>

int main(int argc, char *argv[]) {
    const char *name = argc > 1 ? argv[1] : "world";
    printf("Hello, %s!\n", name);
    return 0;
}

argv[0] is the program path and argv[argc] is NULL — always guard before indexing.

C#C#
var name = args.Length > 0 ? args[0] : "world";
Console.WriteLine($"Hello, {name}!");

Top-level statements (C# 9+): args arrives in Main for free. System.CommandLine is the flag parser.

SwSwift
let args = Array(CommandLine.arguments.dropFirst())
let name = args.first ?? "world"
print("Hello, \(name)!")

arguments[0] is the executable path. SwiftArgumentParser is Apple's flag-parser package.

RbRuby
name = ARGV[0] || 'world'
puts "Hello, #{name}!"

ARGV holds only the arguments. For flags use the built-in optparse: require 'optparse'.