【问题标题】:Check if git branch exists in bash: weird interpolation behavior检查 bash 中是否存在 git 分支:奇怪的插值行为
【发布时间】:2012-11-07 23:27:24
【问题描述】:

我正在尝试查看某个 shell 脚本中是否存在某个分支。

但是,git-branch 在插值时似乎会修改其输出。 (我不知道这里的确切现象或术语)

例如,我正在尝试获取分支数组:

$ git branch
  develop
* master

$ branches=`git branch`
$ echo $branches
develop compiler.sh HOSTNAME index.html master

$ echo `git branch`
develop compiler.sh HOSTNAME index.html master

一种ls-files 似乎妨碍了它。怎么来的?这是巴什吗?吉特?我很困惑。

【问题讨论】:

    标签: git bash shell git-branch


    【解决方案1】:

    git branch 的输出包含 * 字符,表示您当前的分支:

    $ git branch
    develop
    *  master
    

    在你的 shell 中运行 echo * 将打印你的工作目录的 glob:

    compiler.sh HOSTNAME index.html
    

    所以你最初的问题出现了,因为在扩展之后,你实际上是在运行echo develop * master

    为避免这种目录通配行为,您可以在 echo 期间强引用 branches

    $ branches=`git branch`
    $ echo "$branches"
    develop
    *  master
    

    【讨论】:

      【解决方案2】:

      尝试这样做:

      branches=$(git branch | sed 's/\(\*| \)//g')
      

      我建议您使用sed,因为* 字符是globshell,因此它会扩展到当前目录中的所有文件和目录。此外,我删除了不需要的额外空格。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-05
        • 1970-01-01
        • 1970-01-01
        • 2016-06-01
        • 1970-01-01
        • 2021-01-13
        相关资源
        最近更新 更多