简体   繁体   中英

shell script that matches string in git commit message and exports it

I try to write a shell script (bash).

The aim of the script is

  • to get the message of the last git commit
  • grasp any content inside []-parenthesis of the last git commit message
  • export that content into an environment variable called GIT_COMMIT_MESSAGE_CONTEXT

Example:

Last git commit message = "[Stage] - gitlab trial"

Working example: The environment variable exported should be

echo $GIT_COMMIT_MESSAGE_CONTEXT

Stage

I found the following, to get the message of the last git commit:

echo $(git log -1 --pretty=%B)

[Stage] - gitlab trial

I am new to bash-scripts and therefore my trial (see below) is somewhat poor so far. Maybe somebody has more experience to help out here.

My bash script (my-bash-script.sh) looks as follows:

#!/usr/bin/bash

# get last git commit Message
last_git_commit_message="$(git log -1 --pretty=%B)"

export LAST_GIT_COMMIT_MESSAGE="$last_git_commit_message"

I run the bash-script in a terminal as follows:

bash my-bash-script.sh

After closing/re-opening Terminal, I type:

echo $LAST_GIT_COMMIT_MESSAGE


Unfortunately without any result.

Here my questions:

  1. Why do I not get any env-variable echo after running the bash script?
  2. How to deduct the content of []-parenthis of the last git commit message?
  3. How to re-write my script?

The script seems fine, but the approach is flawed. Bash can only export variables to subshells but not vice versa. When you call a script a new shell is started. All variables in that shell, even the exported ones, will be lost after the script exits. See also here .

Some possible ways around that problem:

  1. Source the script.
  2. Let the script print the value and capture its output: variable=$(myScript)
  3. Write the script as a bash function inside your .bashrc .

Depending on what you want to do I recommend 2. or 3. To do 3., put the following in your ~/.bashrc (or ~/.bash_profile if you are using Mac OS) file, start a new shell and use the command extractFromLastCommit as if it were a script.

extractFromLastCommit() {
    export LAST_GIT_COMMIT_MESSAGE=$(
        git log -1 --pretty=%B |
        grep -o '\[[^][]\]' |
        tr -d '\[\]' |
        head -n1 # only take the first "[…]" – remove this line if you want all
    )
}

bash my-bash-script.sh

Starts a new bash process into which your var is exported, then it exits and takes its environment with it.

source my-bash-script.sh

Executes the script in the current shell context and will have the desired effect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM