Search code examples
fish

Check the argument in Fish script?


#!/usr/bin/fish

if count $argv > /dev/null
or not test -d $argv[1]
    echo 'Expected a directory.'
    exit 1
end

I want to check if the argument is a directory and have searched and edited the code many times, but the code above doesn't run as expection still...


Solution

  • count returns a true status if it gets at least one argument.

    So

    if count $argv > /dev/null
    or not test -d $argv[1]
    

    will enter the if-branch if either $argv contains something, or test -d $argv[1] fails.

    The first of these is already wrong, you want

     if not count $argv > /dev/null
     or not test -d $argv[1]
    

    Which will enter the if-branch if no arguments were given or the first argument isn't a directory.

    Now, because of test's issues the bug will manifest weirdly, because:

    count $argv
    or test -d $argv[1]
    

    will only run test -d if there is no $argv[1], so it will run the equivalent of test -d without any additional argument. And because fish's test strictly follows POSIX (one of the few parts of fish to do so), that returns true so you can check things like test "$var" as a short form for test -n "$var".