Search code examples
fishfish-argparse

Parsing arguments in fish shell without argparse


I'm using fish shell and wrote my own little parser function because I found argparse confusing. Basically, if a flag is matched, it uses the information from the following argument. However, I'm assuming my method must introduce bugs as I haven't seen this method used online. Are there advantages to using argparse that I'm missing?

function check_args
 
  for current_arg in (seq 1 (count $argv))

    #grab next argument
    set next_arg $argv[(math $current_arg + 1)]

    switch $argv[$current_arg]
    case -h --help
      usage
      break
    case -t --theme
      echo "theme: " $next_arg
      set -g theme themes/$next_arg.css 
    case -f --format
      echo "format: " $next_arg
      set -g format $next_arg
    case -o --output
      echo "output: " $next_arg
      set -g output $next_arg
    end
  end
end

check_args $argv #calls the function with the passed arguments

Solution

  • With argparse:

    # the -- is required!
    argparse h/help t/theme= f/format= o/output= -- $argv
    or exit 1
    
    # just to inspect the variables
    set -S _flag_h _flag_help _flag_t _flag_theme _flag_f _flag_format _flag_o _flag_output
    
    if set -q _flag_help
        usage
        exit
    end
    
    set theme themes/$_flag_theme.css
    set format $_flag_format
    set output $_flag_output