Search code examples
bashvagrantansible

Vagrant-Ansible/Bash: Verify that a multiquoted block of code exists in file


How could it be verified that the following block of code exists in .bashrc and -if not- append it?

function parse_git_branch {
  git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e "s/* \(.*\)/[\1$(parse_git_dirty)]/"
}

Solution

  • Here is the AWK solution but I must admit it is not “really easy”. Basically, we are building a finite automaton that recognizes the three lines. The exit status is 0 if and only if the pattern was found.

    BEGIN {
        state = 0;
    }
    
    /.*/ {
        if ($0 == "function parse_git_branch {") {
            state = 1;
        } else if ($0 == "  git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e \"s/* \\(.*\\)/[\\1$(parse_git_dirty)]/\"") {
            if (state == 1) {
                state = 2;
            } else {
                state = 0;
            }
        } else if ($0 == "}") {
            if (state == 2) {
                state = 3;
                exit 0;
            } else {
                state = 0;
            }
        } else {
            state = 0;
        }
    }
    
    END {
        # The END rule is always entered, even if we exit via 'exit' so we need to
        # check the state again.
        if (state < 3) {
            exit 1;
        }
    }
    

    The biggest problem I see is that this will answer “no” even if the function is present but formatted a little different (but syntactically equivalent). You could try to improve this by using a more forgiving regular expression pattern instead of string comparison.

    I feel there must be a better solution than this. Maybe using diff?