Search code examples
shellfish

Test for file with a specific type exists


In fish, you can test if a specific file exists with test -e hello.txt, but I'm wondering if there's a way to use wildcard values in the file name, to check for any existence of a file type.

To be more specific, I'm making a quick function that checks for an Xcode Workspace, if found open it, if not then check for an Xcode Project, and if found it opens that, otherwise print an error.

Here is the current implementation:

function xcp
    open *.xcodeproj
end

function xcw
    open *.xcworkspace
end

function xc
    if test -e *.xcworkspace
        xcw
    else if test -e *.xcodeproj
        xcp
    else
        echo "No Xcode Workspace or Project in this directory."
    end
end

It "works" at the minute, but when it doesn't find a workspace or project file, it prints an error about there being no matches. However this is done by default, and I'm wondering if I can hide this somehow.

Here is the error output, when it doesn't find a workspace, but does find a project and opens that:

No matches for wildcard '*.xcworkspace'.  (Tip: empty matches are allowed in 'set', 'count', 'for'.)
~/.config/fish/functions/fish_prompt.fish (line 1): if test -e     *.xcworkspace
                                                           ^
in function 'xc'
    called on standard input

Solution

  • Try counting them:

    function xc
        set -l workspaces *.xcworkspace
        set -l projects   *.xcodeproj
        if test (count $workspaces) -gt 0
            xcw
        else if test (count $projects) -gt 0
            xcp
        else
            echo "No Xcode Workspace or Project in this directory."
        end
    end