How can I programmatically (in a shell script) determine whether or not there are changes?

后端 未结 2 1494
终归单人心
终归单人心 2021-01-05 16:09

I am trying to create a Bash script that knows if there are changes in current working directory. I know that

$ git status

returns a messag

2条回答
  •  余生分开走
    2021-01-05 16:49

    You can check if the variable is set by using the -n expression.

    #!/bin/bash
    CHANGESTOCOMMIT=$(git status | grep 'Changes to be com')
    UNSTAGEDCHANGES=$(git status | grep 'Changes not staged')
    
    # If there are staged changes:
    if [ -n "$CHANGESTOCOMMIT" ]; then
        echo "Changes need to be committed"
    fi
    if [ -n "$UNSTAGEDCHANGES" ]; then
        echo "Changes made but not staged."
    fi
    

    Git tracks changed files that are both staged for committing, and also unstaged files, so your script might want to check both options (or not). The -n operator checks to see if the variable has been set - if it is empty it will return false.

    An alternative is -z which returns True if it is empty (the logical opposite of -n. For a full list of conditional expressions please refer to the Bash Reference Manual.

提交回复
热议问题