New to bash scripting. Know enough to run something simple from intro videos via LinuxAcademy.
I'd like to pull my current Git branch name into the script as a variable and use that variable to make a directory.
From there, I think I can automate the rest of the process.
No script yet, but I do know what I'd like it to do; here it is in plain language.
There are two different good ways to do this, and a number of bad ways.
The most common bad way that you'll find is a variation on this theme:
branch=$(git branch | grep '\\*' | cut -d' ' -f2) # don't do this!
Replace this with:
branch=$(git rev-parse --abbrev-ref HEAD)
Note that if HEAD
is detached (a normal enough state that means not on any branch at all , typically found, eg, when you're in the middle of a rebase that you have not yet finished), this just prints HEAD
. Using this as the branch name often works and does the right thing, so that's OK as long as, well, that's OK. (The cut
version of this prints (HEAD
, which doesn't work.)
The other way to do it is:
branch=$(git symbolic-ref --short HEAD) || exit
(which you can make fancier if you like). With this variant, if you're not on a branch—if you're in that detached HEAD mode—the git symbolic-ref
command will produce a complaint:
fatal: ref HEAD is not a symbolic ref
and the || exit
|| exit
clause will make your script terminate immediately, rather than proceeding to use $branch
as if it were a valid branch name when it's not. Use this code fragment if using the literal string HEAD
instead of an actual branch name is the wrong thing to do.
In bash context, you would use a simple git command
git rev-parse --abbrev-ref HEAD
to output current branch in its short form. ( doc )
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.