Reputation: 7022
I try to write a shell script (bash).
The aim of the script is
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:
Upvotes: 0
Views: 1716
Reputation: 27360
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:
variable=$(myScript)
.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
)
}
Upvotes: 3
Reputation: 32272
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.
Upvotes: 1