debugging - 意外的运算符(operator) [ : git: in bourne shell script 'if' conditional statement

标签 debugging bash shell unix sh

我通过大量 videos 观看了一个优秀的 shell 脚本类(class).现在我认为我对 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

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

为什么会这样?我在 if [ git diff-index --quiet HEAD ] 中使用什么运算符是意外的?

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

最佳答案

在这个声明中:

if [ git diff-index --quiet HEAD ]

[test 命令的别名,因此您实际运行的是...

if test git diff-index --quiet HEAD ]

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

if git diff-index --quiet HEAD

查看if 命令的文档:

$ help if
if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi

if 语句的条件参数是command。通常,test 命令用于使其看起来像其他语言,但您可以将任何 命令放在那里。返回代码为 0 的事物评估为 true,其他任何事物评估为 false。

关于debugging - 意外的运算符(operator) [ : git: in bourne shell script 'if' conditional statement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10588935/

相关文章:

visual-studio - Visual Studio调试

Python:当我的模块返回 "Ellipsis"时,这意味着什么?

bash - VSCode 更改默认终端

linux - 在 awk 中访问 shell 变量但不解释

bash - 如何配置对话框 bash 的取消按钮?

java - 如何使用软断言来避免测试运行执行失败

debugging - 如何在惰性函数式编程语言中实现调试?

regex - 在 bash 中使用从行的中间或末尾提取单词

bash - 如何将 Jupyter Notebook (Windows) shell 更改为 bash

bash - 对于目录中的文件,仅回显文件名(无路径)