ARGPARSE(1)
πΈ ARGPARSE(1) β the fish-shell manual, bestie edition πΈ
okay so this is argparse from the fish-shell manual, and I'm gonna walk you through literally every single thing on the page. buckle up π
π NAME π
argparse β parse options passed to a fish script or function π
β¨ SYNOPSIS β¨
argparse [OPTIONS] OPTION_SPEC ... -- [ARG ...]
π DESCRIPTION π
This command makes it so easy for fish scripts and functions to handle arguments, no cap. Here's the vibe: you pass arguments that define the known options, then a literal --, then the arguments you actually want to be parsed (which might also include their own literal --). argparse then sets variables to tell you which options got passed with which values, sets $argv_opts to the options and their values, and sets $argv to whatever arguments are left over. The usage section below has the deets π
Each option specification (OPTION_SPEC) is written in the domain specific language described further down. All OPTION_SPECs have to appear after any argparse flags and before the -- that separates them from the arguments to be parsed. order matters, bestie β¨
Every option that gets seen in the ARG list will result in variables named _flag_X, where X is the short flag letter and the long flag name (if they're defined). For example a --help option could cause argparse to define one variable called _flag_h and another called _flag_help. two for one, we love to see it π«Ά
The variables get set with local scope (i.e., as if the script had done set -l _flag_X). If the flag is a boolean (that is, it's passed or it isn't, it doesn't have a value) the values are the short and long flags seen. If the option is not a boolean the values will be zero or more values corresponding to the values collected when the ARG list is processed. And if the flag was never seen? The flag variable just won't be set. no variable, no drama π
π₯ OPTIONS π₯
The following argparse options are available. They must appear before all OPTION_SPECs:
-nor--name NAMEβ use NAME in error messages. By default the current function name is used, orargparseif it's run outside of a function. it's giving "who do i blame" energy π-xor--exclusive OPTIONSβ a comma separated list of options that are mutually exclusive. You can use this more than once to define multiple sets of mutually exclusive options. You give either the short or the long version of each option, and you still need to otherwise define the options yourself. iconic but high-maintenance π-Nor--min-args NUMBERβ the minimum number of acceptable non-option arguments. The default is zero.-Xor--max-args NUMBERβ the maximum number of acceptable non-option arguments. The default is infinity. yes, infinity, go off βΎοΈ-uor--move-unknownβ allow unknown options, and move them from$argvto$argv_opts. By default, unknown options are treated as if they take optional arguments (i.e. have option spec=?).
The above means that if a group of short options contains an unknown short option followed by a known short option, the known short option is treated as an argument to the unknown one (e.g. --move-unknown h -- -oh will treat h as the argument to -o, and so _flag_h will not be set). In contrast, if the known option comes first (and does not take any arguments), the known option will be recognised (e.g. argparse --move-unknown h -- -ho will set $_flag_h to -h). yes this is a whole thing, read it twice if u need π«
-ior--ignore-unknownβ deprecated. This is like--move-unknown, except that unknown options and their arguments are kept in$argvand not moved to$argv_opts. Unlike--move-unknown, this option makes it impossible to distinguish between an unknown option and a non-option argument that starts with a-(since any--separator in$argvwill be removed). so yeah, deprecated for a reason, tread carefully π-Sor--strict-longoptsβ this makes the parsing of long options more strict. In particular, without this flag, iflongis a known long option flag,--longand--long=<value>can be abbreviated as:-longand-long=<value>, but only if there is no short flagl.--loand--lo=<value>, but only if there is no other long flag that starts withlo. Similarly with any other non-empty prefix oflong.-loand-lo=<value>(i.e. combining the above two).
With the --strict-longopts flag, the above three are parse errors: one must use the syntax --long or --long=<value> to use a long option called long. no shortcuts, bestie, we do it properly π§
This flag has no effect on the parsing of unknown options (which are parsed as if this flag is on).
heads up: this option may be on all the time in the future, so do not rely on the behaviour without it. plan ahead, queen π
--unknown-arguments KINDβ this option implies--move-unknown, unless--ignore-unknownis also given. This will modify the parsing behaviour of unknown options depending on the value of KIND:optional(the default), allows each unknown option to take an optional argument (i.e. as if it had=?or=*in its option specification). For example,argparse --ignore-unknown --unknown-arguments=optional ab -- -u -a -ubwill set_flag_abut not_flag_b, as thebis treated as an argument to the second use of-u.requiredrequires each unknown option to take an argument (i.e. as if it had=or=+in its option specification). If the above example was changed to use--unknown-arguments=required, neither_flag_anor_flag_bwould be set: the-awill be treated as an argument to the first use of-u, and thebas an argument to the second.noneforbids each unknown option from taking an argument (i.e. as if it had no=in its option specification). If the above example was changed to use--unknown-arguments=none, both_flag_aand_flag_bwould be set, as neither use of-uwill be passed as taking an argument.
Note that the above assumes that unknown long flags use the -- "GNU-style" (e.g. if KIND is none, and there is no bar long option, -bar is interpreted as three short flags, b, a, and r; but if bar is known, -bar is treated the same as --bar). iykyk π
When using --unknown-arguments=required, you will get an error if the provided arguments end in an unknown option, since it has no argument. Similarly, with --unknown-arguments=none, you will get an error if you use the --flag=value syntax and flag is an unknown option. errors! drama! but like, correct drama π
-sor--stop-nonoptβ causes scanning the arguments to stop as soon as the first non-option argument is seen. Among other things, this is useful to implement subcommands that have their own options. very main-character energy for your subcommands π-hor--helpβ displays help about using this command. classic, iconic, always there for u π«Ά
π¦ USAGE π¦
To use this command, pass the option specifications (OPTION_SPEC), a mandatory --, and then the arguments to be parsed.
A simple example:
argparse 'h/help' 'n/name=' -- $argv
or return
If $argv is empty then there is nothing to parse and argparse returns zero to indicate success. If $argv is not empty then it is checked for flags -h, --help, -n and --name. If they're found they get removed from the arguments and local variables called _flag_OPTION are set so the script can determine which options were seen. If $argv doesn't have any errors, like an unknown option or a missing mandatory value for an option, then argparse exits with a status of zero. Otherwise it writes appropriate error messages to stderr and exits with a status of one. sad but fair π
The or return means that the function returns argparse's status if it failed, so if it goes on, argparse succeeded. slay, short-circuit logic β¨
To use the flags argparse has extracted:
# Checking for _flag_h and _flag_help is equivalent
# We check if it has been given at least once
if set -ql _flag_h
echo "Usage: my_function [-h | --help] [-n | --name=NAME]" >&2
return 1
end
set -l myname somedefault
set -ql _flag_name[1]
and set myname $_flag_name[-1] # here we use the *last* --name=
Any characters in the flag name that are not valid in a variable name (like - dashes) will be replaced with underscores. cute little name glow-up π
The -- argument is required. You do not have to include any option specifications or arguments after the -- but you must include the --. For example, this is acceptable:
set -l argv foo
argparse 'h/help' 'n/name' -- $argv
argparse --min-args=1 -- $argv
But this is not:
set -l argv
argparse 'h/help' 'n/name' $argv
The first -- seen is what allows the argparse command to reliably separate the option specifications and options to argparse itself (like --move-unknown) from the command arguments, so it is required. it's literally the whole boundary, respect it π€
π OPTION SPECIFICATIONS π
Each option specification consists of:
- An optional alphanumeric short flag character.
- An optional long flag name preceded by a
/. If neither a short flag nor long flag are present, an error is reported. rude but necessary π- If there is no short flag, and the long flag name is more than one character, the
/can be omitted. - For backwards compatibility, if there is a short and a long flag, a
-can be used in place of the/, if the short flag is not to be usable by users (in which case it will also not be exposed as a flag variable). sneaky legacy behaviour, but noted π΅οΈ
- If there is no short flag, and the long flag name is more than one character, the
- Nothing if the flag is a boolean that takes no argument or is an integer flag, or
=if it requires a value and only the last instance of the flag is saved, or=?if it takes an optional value and only the last instance of the flag is saved, or=+if it requires a value and each instance of the flag is saved, or=*if it takes an optional value and each instance of the flag is saved, storing the empty string when the flag was not given a value. empty string but make it intentional β¨
- Optionally a
&, indicating that the option and any attached values are not to be saved in$argvor$argv_opts. This does not affect the_flag_variables. so the flag vars still show up, the argv just stays clean, we love a tidy queen π - Nothing if the flag is a boolean that takes no argument, or
!followed by fish script to validate the value. Typically this will be a function to run. If the exit status is zero the value for the flag is valid. If non-zero the value is invalid. Any error messages should be written to stdout (not stderr). See the section on Flag Value Validation for more information. yes, stdout, i said what i said π«Ά
See the fish_opt command for a friendlier but more verbose way to create option specifications. it's giving "there's a helper for that" πΈ
If a flag is not seen when parsing the arguments then the corresponding _flag_X var(s) will not be set.
π’ INTEGER FLAG π’
Okay so sometimes commands take numbers directly as options, like foo -55. Iconic behavior, honestly. To allow this, one option spec can have the # modifier so that any integer will be understood as this flag, and the last number will be given as its value (as if = was used).
The # must follow the short flag letter (if any), and other modifiers like = are not allowed, except for - (for backwards compatibility):
m#maximum
This does not read numbers given as +NNN, only those that look like flags β -NNN.
π¨ NOTE: OPTIONAL ARGUMENTS π¨
An option defined with =? or =* can take optional arguments. Optional arguments have to be directly attached to the option they belong to.
That means the argument will only be used for the option if you use it like:
cmd --flag=value
# or
cmd -fvalue
but not if used like:
cmd --flag value
# "value" here will be used as a positional argument
# and "--flag" won't have an argument.
If this weren't the case, using an option without an optional argument would be difficult if you also wanted to use positional arguments.
For example:
grep --color auto
# Here "auto" will be used as the search string,
# "color" will not have an argument and will fall back to the default,
# which also *happens to be* auto.
grep --color always
# Here grep will still only use color "auto"matically
# and search for the string "always".
This isn't specific to argparse but common to all things using getopt(3) (if they have optional arguments at all). That grep example is how GNU grep actually behaves.
π‘οΈ FLAG VALUE VALIDATION π‘οΈ
Sometimes you need to validate the option values. For example, that it is a valid integer within a specific range, or an ip address, or something entirely different. You can always do this after argparse returns but you can also request that argparse perform the validation by executing arbitrary fish script. To do so append an ! (exclamation-mark) then the fish script to be run. When that code is executed three vars will be defined:
_argparse_cmdβ will be set to the value of the value of theargparse--namevalue._flag_nameβ will be set to the short or long flag that being processed._flag_valueβ will be set to the value associated with the flag being processed.
These variables are passed to the function as local exported variables.
The script should write any error messages to stdout, not stderr. It should return a status of zero if the flag value is valid otherwise a non-zero status to indicate it is invalid.
fish ships with a _validate_int function that accepts a --min and --max flag. Let's say your command accepts a -m or --max flag and the minimum allowable value is zero and the maximum is 5. You would define the option like this: m/max=!_validate_int --min 0 --max 5. The default if you call _validate_int without those flags is to check that the value is a valid integer with no limits on the min or max value allowed.
Here are some examples of flag validations:
# validate that a path is a directory
argparse 'p/path=!test -d "$_flag_value"' -- --path $__fish_config_dir
# validate that a function does not exist
argparse 'f/func=!not functions -q "$_flag_value"' -- -f alias
# validate that a string matches a regex
argparse 'c/color=!string match -rq \'^#?[0-9a-fA-F]{6}$\' "$_flag_value"' -- -c 'c0ffee'
# validate with a validator function
argparse 'n/num=!_validate_int --min 0 --max 99' -- --num 42
π EXAMPLE OPTION_SPECS π
Some OPTION_SPEC examples:
h/helpβ means that both-hand--helpare valid. The flag is a boolean and can be used more than once. If either flag is used then_flag_hand_flag_helpwill be set to however either flag was seen, as many times as it was seen. So it could be set to-h,-hand--help, andcount $_flag_hwould yield"3".helpβ means that only--helpis valid. The flag is a boolean and can be used more than once. If it is used then_flag_helpwill be set as above. Alsoh-help(with an arbitrary short letter) for backwards compatibility.help&β is similar (it will remove--helpfrom$argv), the difference is that--helpwill not be placed in$argv_opts.longonly=β is a flag--longonlythat requires an option, there is no short flag or even short flag variable.n/name=β means that both-nand--nameare valid. It requires a value and can be used at most once. If the flag is seen then_flag_nand_flag_namewill be set with the single mandatory value associated with the flag.n/name=?β means that both-nand--nameare valid. It accepts an optional value and can be used at most once. If the flag is seen then_flag_nand_flag_namewill be set with the value associated with the flag if one was provided else it will be set with no values.n/name=*β is similar, but the flag can be used more than once. If the flag is seen then_flag_nand_flag_namewill be set with the values associated with each occurrence. Each value will be the value given to the option, or the empty string if no value was given.name=+β means that only--nameis valid. It requires a value and can be used more than once. If the flag is seen then_flag_namewill be set with the values associated with each occurrence.xβ means that only-xis valid. It is a boolean that can be used more than once. If it is seen then_flag_xwill be set as above./xβ is similar, but only--xis valid (instead of-x).x=,x=?, andx=+β are similar to then/nameexamples above but there is no long flag alternative to the short flag-x.#max(or#-max) β means that flags matching the regex"^--?\d+$"are valid. When seen they are assigned to the variable_flag_max. This allows any valid positive or negative integer to be specified by prefixing it with a single-. Many commands support this idiom. For examplehead -3 /a/fileto emit only the first three lines of/a/file.n#maxβ means that flags matching the regex"^--?\d+$"are valid. When seen they are assigned to the variables_flag_nand_flag_max. This allows any valid positive or negative integer to be specified by prefixing it with a single-. Many commands support this idiom. For examplehead -3 /a/fileto emit only the first three lines of/a/file. You can also specify the value using either flag:-n NNNor--max NNNin this example.#longonlyβ causes the last integer option to be stored in_flag_longonly.
After parsing the arguments the argv variable is set with local scope to any values not already consumed during flag processing. If there are no unbound values the variable is set but count $argv will be zero. Similarly, the argv_opts variable is set with local scope to the arguments that were consumed during flag processing. This allows forwarding $argv_opts to another command, together with additional arguments.
If an error occurs during argparse processing it will exit with a non-zero status and print error messages to stderr.
π EXAMPLES π
A simple use, bestie:
argparse h/help -- $argv
or return
if set -q _flag_help
# TODO: Print help here
return 0
end
This supports one option: -h / --help. Any other option is an error. If it is given it prints help and exits.
How fish_add_path - add to the path <> parses its args:
argparse -x g,U -x P,U -x a,p g/global U/universal P/path p/prepend a/append h/help m/move v/verbose n/dry-run -- $argv
There are a variety of boolean flags, all with long and short versions. A few of these cannot be used together, and that is what the -x flag is used for. -x g,U means that --global and --universal or their short equivalents conflict, and if they are used together you get an error. In this case you only need to give the short or long flag, not the full option specification.
After this it figures out which variable it should operate on according to the --path flag:
set -l var fish_user_paths
set -q _flag_path
and set var PATH
# ...
# Check for --dry-run.
# The "-" has been replaced with a "_" because
# it is not valid in a variable name
not set -ql _flag_dry_run
and set $var $result
An example of using $argv_opts to forward known options to another command, whilst adding new options:
function my-head
# The following option is the only existing one to head that takes arguments
# (we will forward it verbatim).
set -l opt_spec n/lines=
# --qwords is a new option, but --bytes is an existing one which we will modify below
set -a opt_spec "qwords=&" "c/bytes=&"
argparse --strict-longopts --move-unknown --unknown-arguments=none $opt_spec -- $argv || return
if set -q _flag_qwords
# --qwords allows specifying the size in multiples of 8 bytes
set -a argv_opts --bytes=(math -- $_flag_qwords \* 8 || return)
else if set -q _flag_bytes
# Allows using a 'q' suffix, e.g. --bytes=4q to mean 4*8 bytes.
if string match -qr 'q$' -- $_flag_bytes
set -a argv_opts --bytes=(math -- (string replace -r 'q$' '*8' -- $_flag_bytes) || return)
else
# Keep the users setting
set -a argv_opts --bytes=$_flag_bytes
end
end
if test (count $argv) -eq 0
# Default to heading /dev/kmsg (whereas head defaults to stdin)
set -l argv /dev/kmsg
end
# Call the real head with our modified options and arguments.
head $argv_opts -- $argv
end
The argparse call above saves all the options we do not want to process in $argv_opts. (The --qwords and --bytes options are not saved there as their option spec's end in a ~). The code then processes the --qwords and --bytess options using the the $_flag_OPTION variables, and puts the transformed options in $argv_opts (which already contains all the original options, other than --qwords and --bytes).
Note that because the argparse call above uses --move-unknown and --unknown-arguments=none, we only need to tell it the arguments to head that take a value. This allows the wrapper script to accurately work out the non-option arguments (i.e. $argv, the filenames that head is to operate on). Using --unknown-arguments=optional and explicitly listing all the known options to head however would have the advantage that if head were to add new options, they could still be used with the wrapper script using the "stuck" form for arguments (e.g. -o<arg>, or --opt=<arg>).
Note that the --strict-longopts is required to be able to correctly pass short options, e.g. without it my-head -q --bytes 10q, will actually parse the -q as shorthand for --qwords.
π Copyright π
fish-shell developers
Okay that's the whole page, bestie β ARGPARSE(1), version 4.9, dated Sep 08, 2026, brought to you by the fish-shell developers. Bye, go be the main character of your shell! π
β¨
π¦ where this page comes from
- arch rolling: fish 4.9.3-1 Β· GPL-2.0-only AND BSD-3-Clause AND ISC AND MIT AND PSF-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms