Table of Contents

    Command Line Arguments

    PROGRAMMING & CLI

    Command Line Arguments — The Complete Guide

    Understand command-line arguments: what they are, how programs receive them, and how to read and parse them across languages.

    Introduction

    Command-line arguments are values you pass to a program when you launch it from a terminal or command prompt. They let you control a program's behaviour without changing its code — telling it which file to open, which mode to run in, or how verbose to be. When you type something like python script.py input.txt --verbose, the words after the program name are its command-line arguments, and the operating system delivers them to the program at startup.

    In one line: Command-line arguments are inputs you hand a program at launch to change what it does — no code edits needed.

    Real-World Analogy

    Instructions to a Taxi Driver

    When you get in a taxi, you don't rebuild the car — you just tell the driver your destination, preferred route, and whether to hurry. Command-line arguments are those instructions: the program (the taxi) is already built, and you simply pass details at the start of the trip to steer its behaviour.

    Anatomy of a Command

    A typical command is made of several distinct parts:

    python  backup.py  data.csv  --output  out.zip  --verbose
      |         |          |          |         |         |
    program   script   positional   option    value     flag
              name      argument
    Part Meaning
    Positional argument A value identified by its position (e.g. data.csv)
    Option / flag A named switch starting with - or -- (e.g. --output)
    Option value The value that follows an option (e.g. out.zip)
    Boolean flag An on/off switch with no value (e.g. --verbose)

    Prerequisites

    Before You Start

    • Ability to run programs from a terminal or command prompt
    • Basic understanding of functions and variables
    • Familiarity with at least one language (Python, C, Java, or JavaScript)
    • Knowledge of how to navigate directories in the shell
    • A code editor and a runtime installed

    Reading Arguments in Python (sys.argv)

    The simplest way in Python is sys.argv, a list of strings. The first element is the script name.

    import sys
    
    # sys.argv is a list of strings
    print("Script name:", sys.argv[0])
    print("Arguments:", sys.argv[1:])
    
    # Example: python demo.py hello 42
    # Script name: demo.py
    # Arguments: ['hello', '42']
    Remember Everything in sys.argv is a string — even numbers. Convert with int() or float() before doing math.

    A small practical example

    import sys
    
    if len(sys.argv) < 3:
        print("Usage: python add.py <a> <b>")
        sys.exit(1)
    
    a = int(sys.argv[1])
    b = int(sys.argv[2])
    print("Sum:", a + b)

    The Better Way: argparse

    For anything beyond trivial scripts, use argparse — it adds validation, help, and typed values automatically.

    import argparse
    
    parser = argparse.ArgumentParser(description="Add two numbers")
    parser.add_argument("a", type=int)
    parser.add_argument("b", type=int)
    parser.add_argument("--verbose", action="store_true")
    args = parser.parse_args()
    
    result = args.a + args.b
    if args.verbose:
        print(f"{args.a} + {args.b} = {result}")
    else:
        print(result)

    Command-Line Arguments in Other Languages

    C

    #include <stdio.h>
    
    // argc = argument count, argv = argument values
    int main(int argc, char *argv[]) {
        printf("Program: %s\n", argv[0]);
        for (int i = 1; i < argc; i++) {
            printf("Arg %d: %s\n", i, argv[i]);
        }
        return 0;
    }

    Java

    public class Main {
        public static void main(String[] args) {
            // args does NOT include the program name
            System.out.println("Count: " + args.length);
            for (String arg : args) {
                System.out.println(arg);
            }
        }
    }

    JavaScript (Node.js)

    // process.argv: [node, script, ...args]
    const args = process.argv.slice(2);
    console.log("Arguments:", args);
    
    // Example: node app.js hello 42
    // Arguments: [ 'hello', '42' ]

    How Each Language Exposes Them

    Language Access Via Includes Program Name?
    Python sys.argv Yes (index 0)
    C / C++ argc, argv[] Yes (argv[0])
    Java String[] args No
    JavaScript (Node) process.argv Yes (node + script)
    Go os.Args Yes (index 0)

    Common Conventions

    1

    Short Options -v

    A single dash + one letter.

    Quick to type; often combinable (e.g. -la means -l -a).

    2

    Long Options --verbose

    Two dashes + a full word.

    Self-documenting and clear; preferred in scripts for readability.

    3

    The -- Separator

    Marks the end of options.

    Everything after -- is treated as positional, even if it starts with a dash.

    Argument Count

    If a program receives \(n\) arguments after its name, the total number of tokens the OS passes (including the program name itself) is:

    \[ \text{argc} = n + 1 \]

    This is why in C, argc is always at least \(1\) — the program name always occupies argv[0].

    Best Practices

    Do This

    • Use a proper parser (like argparse) instead of manual indexing for real tools
    • Always validate and convert argument types before using them
    • Provide a clear usage/help message when arguments are missing or wrong
    • Follow conventions: short -v and long --verbose options
    • Give sensible defaults so common cases need fewer arguments
    • Exit with a non-zero status code on invalid input

    Common Mistakes

    Bad Assuming arguments are numbers — they arrive as strings, so sys.argv[1] + 1 fails or concatenates.
    Good Convert explicitly: int(sys.argv[1]) + 1.
    Bad Accessing sys.argv[1] without checking length — crashes with an IndexError when no argument is given.
    Good Check len(sys.argv) first, or let argparse handle missing arguments gracefully.

    Interview Questions

    Question Short Answer
    What are command-line arguments? Values passed to a program at launch to control its behaviour.
    What is in sys.argv[0]? The name/path of the script being run.
    Are arguments strings or numbers? Always strings — you must convert them yourself.
    Difference between short and long options? Short use one dash + letter (-v); long use two dashes + word (--verbose).
    Why use argparse over sys.argv? It adds validation, type conversion, help text, and error handling automatically.

    Quick Revision

    Language Read Arguments
    Python (simple) sys.argv
    Python (robust) argparse
    C argc, argv[]
    Java String[] args
    Node.js process.argv

    Key Takeaways

    Command-line arguments let you control a program at launch without touching its code. Every language exposes them (Python's sys.argv, C's argv, Java's args) as strings — so validate and convert. For real tools, use a dedicated parser like argparse for help, types, and error handling.