Search code examples
gitshellfish

Fish Shell: How to interpret git response?


For my workspace environment I'm currently creating a script to easily switch between my development and release branches. Unfortunately the repo's do not always have similar branch name, therefor I check if the branch exists and if the branch has already been merged to master. If the branch has not been merged to master, I know I have the latest release branch.

        set repo_has_changes (git status --porcelain --untracked-files=no)

        if test -n $repo_has_changes
            echo 'Repo has changes...'
        else
            git checkout master

            for b in $releaseVersions
                set branch_on_origin (git branch -r --list origin/$b)
                set branch_not_merged_to_master (git branch -r --list --no-merged master origin/$b)

                if test -n $branch_on_origin
                    if test -z $branch_not_merged_to_master
                        git checkout $b
                        git pull
                        break
                    end
                end
            end
        end

In my ignorance I thought I store the result of my git command, and store it in a variable. I interpreted it as string. According to the fish documentation I can test if a string is non-zero.

-n STRING returns true if the length of STRING is non-zero.

This script will always echo 'Repo has changes...' while I'm 100% sure it doesn't have changes. If I echo $repo_has_changes I see an empty line. Also if I check the length of the string (just in case string returns spaces? xD ) it also returns an empty line. So my assumption that $repo_has_changes is a string might be wrong. Also I'm not certain that I'm able to store the git result in this fashion. Unfortunately I wasn't able to find a good source for this.


Solution

  • Unfortunately, fish's test is one of the few parts that follow POSIX to the letter, and that specifies that test with any one argument has to return true, to facilitate uses like test "thestring". Unfortunately this also means that test -n has to return true.

    Which indeed means you need to quote any variable you pass to test:

    test -n "$branch_on_origin"
    

    and

    test -z "$branch_not_merged_to_master"