Search code examples
fish

fish: swallow flags from $argv (context: replace rm with KDE trash)


I already have most of it working but I want to swallow flags so I don't get an error like this:

/t/temp-5969 $ trash -rf fish-functions/
kioclient: Unknown option 'rf'.
kioclient: Use --help to get a list of available command line options.

I have this so far:

/t/temp-5969 $ type trash
trash is a function with definition
function trash
    kioclient move $argv trash:/
end

(to replace rm: abbr rm trash)

I want it to ignore -rf so it will still work either way so my muscle memory doesn't mess up when I switch between bash and fish

To accomplish this I want to build a function to swallow the flags from $argv


Solution

  • I would do this

    function trash
        while test (count $argv) -gt 0
            switch $argv[1]
                case --
                    set argv $argv[2..-1]
                    break
                case '-*'
                    set argv $argv[2..-1]
                case '*'
                    break
            end
        end
    
        kioclient move $argv trash:/
    end
    

    It would be nice if argparse could help, but that works when you know specifically what options you need to parse.

    Note you may still be "vulnerable": to deal with filenames starting with a dash, you can do

    rm -- -filename-starts-with-a-dash
    rm ./-filename-starts-with-a-dash
    

    With your function, you'll have to use the 2nd one.