Create Custom Fish Switches

239 views Asked by At

I am working on a fish shell function named quick( see here ) and I would like to add some switches to it.

For example quick -l to list all pathLabels.

Fish documentation does not seem to provide such information.

My questions are,

  • What is the best way to enhance a functions' functionality with switches in fish ?
  • Is it possible to expand an existing command with new switches ?
  • Does this relate to the similar topic for bash/shell ?

I have come across several related information out there like "How do I parse command line arguments in bash?" but have not found a clear and fish specific answer to those questions. Any help please, it will be appreciated !

Note: Checking > functions alias as an example, seems that just $argv is used within a switch statement.

1

There are 1 answers

0
glenn jackman On BEST ANSWER

You can use getopt. It's pretty verbose. Here's an example that just looks for -h or --help

function foobar
    set -l usage "usage: foobar [-h|--help] subcommand [args...]
                ... more help text ...
"
    if test (count $argv) -eq 0
        echo $usage
        return 2
    end

    # option handling, let's use getopt(1), and assume "new" getopt (-T)
    set -l tmp (getopt -o h --long help -- $argv)
    or begin
        echo $usage
        return 2
    end

    set -l opts
    eval set opts $tmp

    for opt in $opts
        switch $opt
            case -h --help
                echo $usage
                return 0
            case --
                break
            case '-*'
                echo "unknown option: $opt"
                echo $usage
                return 1
        end
    end

    switch $argv[1]
        case subcommand_a
            ... etc