Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test for file with a specific type exists

Tags:

shell

fish

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
like image 740
Christopher Hannah Avatar asked Jul 14 '17 08:07

Christopher Hannah


People also ask

How do you check if a file exists or not empty?

You can use the find command and other options as follows. The -s option to the test builtin check to see if FILE exists and has a size greater than zero. It returns true and false values to indicate that file is empty or has some data.

How do you check if a directory contains a file in bash?

In order to check if a file exists in Bash using shorter forms, specify the “-f” option in brackets and append the command that you want to run if it succeeds. [[ -f <file> ]] && echo "This file exists!" [ -f <file> ] && echo "This file exists!" [[ -f /etc/passwd ]] && echo "This file exists!"


1 Answers

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
like image 73
glenn jackman Avatar answered Sep 21 '22 10:09

glenn jackman