意外的运算符[:git:在bourne shell脚本中'if'条件语句

Tom*_*Tom 2 unix debugging bash shell sh

我通过大量视频观看了一个优秀的shell脚本课程.现在我认为我对Bourne shell非常熟悉,我决定编写我的第一个shell脚本.

脚本目标:检查git工作目录是否干净.如果是这样,请将工作目录覆盖到名为的分支deployment.最后,将部署分支推送到origin.

我最终得到了这段代码:

#!/bin/sh

######################################################
# Deploys working directory to git deployment branch.
# Requires that the working directory is clean.
######################################################

#check if the working directory is clean
if [ git diff-index --quiet HEAD ]
then
    if [ git branch -f deployment ]
    then
        if [ git push origin deployment ]
        then
            echo
            echo "OK. Successfully deployed to git deployment branch."
            echo
            exit 0 #success
        else
            echo
            echo "Error: failed to push deployment branch to origin."
            echo
            exit 1 #failure
        fi
    else
        echo
        echo "Error: failed to create or overwrite deployment branch."
        echo
        exit 1 #failure
    fi
else
    echo
    git status #show the status of the working directory
    echo
    echo "Error: working directory is not clean. Commit your changes first..."
    echo
    exit 1 #failure
fi
Run Code Online (Sandbox Code Playgroud)

不幸的是,这似乎给了我一个错误: ./tools/deploygit: 9: [: git: unexpected operator

为什么会这样?我使用的操作员if [ git diff-index --quiet HEAD ]是出乎意料的?

作为奖励,您对如何提高此脚本的效率,逻辑或可读性有任何建议或提示吗?

lar*_*sks 8

在这个声明中:

if [ git diff-index --quiet HEAD ]
Run Code Online (Sandbox Code Playgroud)

[test命令的别名,所以你实际运行的是......

if test git diff-index --quiet HEAD ]
Run Code Online (Sandbox Code Playgroud)

......这不是你的意思.您无需使用该test命令来评估命令的结果; 你应该这样做:

if git diff-index --quiet HEAD
Run Code Online (Sandbox Code Playgroud)

看一下该if命令的文档:

$ help if
if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi
Run Code Online (Sandbox Code Playgroud)

if语句的条件参数是命令.通常,该test命令用于使其看起来像其他语言,但您可以在其中放置任何命令.返回代码为0的东西评估为true,其他任何东西的评估结果为false.