Skip to content

Parser les arguments de ligne de commande snippet

Lire ce que l'utilisateur a tapé après le nom de ton programme.

Lire ce que l'utilisateur a tapé après le nom de ton programme. Le tableau brut n'est jamais qu'à un saut — argv dans l'héritage C, ARGV en Ruby, process.argv sous Node — mais chaque runtime le décale différemment (Node cache le runtime et le chemin du script dans les cases 0 et 1), et parser les flags à la main devient vite moche. Sers-toi du parser fourni dès que tu as des flags avec valeurs : flag en Go, argparse en Python.

Recette exécutable · 10 langages
System & CLIcliargvflags

Every language

10 langages, 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'.