简体   繁体   English

Bash / Git-如何使用当前的git分支名称制作脚本

[英]Bash / Git - How to make a script using current git branch name

New to bash scripting. bash脚本的新手。 Know enough to run something simple from intro videos via LinuxAcademy. 足够了解如何通过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. 我想将当前的Git分支名称作为变量提取到脚本中,并使用该变量创建目录。

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. 这里用简单的语言。

  1. cd somedir/dir cd somedir /目录
  2. git branch (pull name as a variable) git branch(将名称作为变量拉出)
  3. mkdir (as branch name variable) mkdir(作为分支名称变量)
  4. cd (newdir) 光盘(newdir)
  5. touch xyz.html 触摸xyz.html
  6. mkdir css img mkdir css img
  7. cd css touch xyz.css reset.css cd css touch xyz.css reset.css
  8. cd ../.. cd ../ ..

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 . 请注意,如果HEAD分离 (正常的状态,意味着通常根本不在任何分支上 ,例如,当您处于尚未完成的变基中间时),这只会打印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.) (此打印版的cut版本(HEAD 无效 )。

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: 使用此变体,如果您不在分支上(如果您处于分离的HEAD模式),则git symbolic-ref命令将产生投诉:

fatal: ref HEAD is not a symbolic ref

and the || exit || 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. || exit子句将使您的脚本立即终止,而不是继续使用$branch ,就好像它不是有效的分支名称一样。 Use this code fragment if using the literal string HEAD instead of an actual branch name is the wrong thing to do. 如果使用文字字符串HEAD而不是实际的分支名称是错误的事情,请使用此代码片段。

In bash context, you would use a simple git command 在bash上下文中,您将使用一个简单的git命令

git rev-parse --abbrev-ref HEAD

to output current branch in its short form. 以简写形式输出电流分支。 ( doc ) doc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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