C.W.K.
Stream
Lesson 05 of 10 · published

Commands, Arguments, Flags

~15 min · command, argument, flag, getopt

Level 0Window Tourist
0 XP0/95 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

The grammar of every command line

Every command in the shell follows the same shape: command [flags] [arguments]. The command is the executable. Flags (or options) modify behavior. Arguments are the things you act on. Once you can read this shape, every --help page in the world stops being scary.

Short flags vs long flags

POSIX commands use single-letter flags: -l, -a, -h. GNU and modern tools also accept long flags: --long-format, --all, --help. Short flags can be stacked: ls -lah is the same as ls -l -a -h. Long flags cannot be stacked but are self-documenting.

Flag arguments

Some flags take a value: -o output.txt, --output output.txt, or --output=output.txt. The space form is POSIX-classic; the equals form is GNU-style. Both are valid for tools that support them. Short flags with values usually drop the space: -ofile.txt works for many BSD tools.

The mighty -- separator

If a filename starts with a dash, the shell will read it as a flag. The -- token tells the command "every word after this is a positional argument, not a flag." rm -- -ohnoes.txt deletes the file -ohnoes.txt instead of complaining about an unknown -o option.

Reading --help output

The synopsis line is the truth: USAGE: tar [OPTION]... [FILE]... means "any number of options, then any number of files." Square brackets are optional, ellipsis means repeatable, vertical bar means "choose one." Once you trust the synopsis, the rest of the help page is just listing each option in detail.

Code

Same flags, different forms·bash
# Stacked short flags
ls -lah ~
# Equivalent long flags
ls --format=long --all --human-readable ~
# Mixed (legal everywhere)
ls -l --all -h ~
Filename starting with dash — use --·bash
touch -- -weird.txt
ls -- -weird.txt
rm -- -weird.txt           # safe
# rm -weird.txt            # would explode: rm: illegal option -- w

External links

Exercise

Run ls --help | head -20 (Linux) or man ls (macOS). Find the synopsis line. Then run ls -lah ~, ls -l -a -h ~, and ls --all --long ~ and confirm they produce equivalent output. Now create a file named -test.txt with touch -- -test.txt and remove it with rm -- -test.txt.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.