Skip to content

Arguments

Arguments are declared and customized similarly to options, but are provided on the command line positionally instead of by name. Arguments are declared with argument(), and the order that they are declared defines the order that they must be provided on the command line.

Basic Arguments

By default, argument takes a single String value which is required to be provided on the command line.

class Hello : CliktCommand() {
    val name by argument()
    override fun run() {
        echo("Hello $name!")
    }
}
$ ./hello Foo
Hello Foo!

Arguments appear in the usage string, but listed in the help page unless you set their help value. It’s usually clearer to document arguments in the command help.

class Cp : CliktCommand(
    help = "Copy <source> to <dest>, or multiple <source>(s) to directory <dest>."
) {
    private val source by argument().file(mustExist = true).multiple()
    private val dest by argument().file()
    override fun run() {
        // ...
    }
}
Usage: cp [<options>] [<source>]... <dest>

  Copy <source> to <dest>, or multiple <source>(s) to directory <dest>.

Options:
  -h, --help         Show this message and exit

Variadic Arguments

Like options, arguments can take any fixed number of values, which you can change with functions like pair and triple. Unlike options, arguments can also take a variable (or unlimited) number of values. This is common with file path arguments, since they are frequently expanded with a glob pattern on the command line.

Variadic arguments are declared with multiple. You can declare any number of arguments with fixed numbers of values, but only one variadic argument in a command.

class Copy : CliktCommand() {
    val source: List<Path> by argument().path(mustExist = true).multiple()
    val dest: Path by argument().path(canBeFile = false)
    override fun run() {
        echo("Copying files $source to $dest")
    }
}
$ ./copy file.* out/
Copying files [file.txt, file.md] to out/

You can also use unique to discard duplicates:

val source: Set<Path> by argument().path(mustExist = true).multiple().unique()

Option-Like Arguments (Using --)

Clikt normally parses any value that starts with punctuation as an option, which allows users to intermix options and arguments. However, sometimes you need to pass a value that starts with punctuation to an argument. For example, you might have a file named -file.txt that you want to use as an argument.

Clikt supports the POSIX convention of using -- to force all following values to be treated as arguments. Any values before the -- will be parsed normally.

class Touch : CliktCommand() {
    val verbose by option().flag()
    val files by argument().multiple()
    override fun run() {
        if (verbose) echo(files.joinToString("\n"))
    }
}
$ ./touch --foo.txt
Usage: touch [<options>] [<files>]...

Error: no such option: "--foo.txt".
$ ./touch --verbose -- --foo.txt bar.txt
--foo.txt
bar.txt