以下代码产生错误“expect expression expected”:
for SOURCE_PATH in work/sources/*; do
git diff --exit-code &>/dev/null || SOMETHING_TO_COMMIT=$?
if [ "$SOMETHING_TO_COMMIT" -eq "0" ] || [ "$SOMETHING_TO_COMMIT" -eq "" ] ; then
echo "NOTHING TO COMMIT FOR $SOURCE_PATH";
else
echo "COMMIT FOR $SOURCE_PATH"
git -C "$DIR/$SOURCE_PATH" commit -F ${COMMIT_MESSAGE_FILE}
fi
done
错误在线if [ "$SOMETHING_TO_COMMIT" -eq "0" ] || [ "$SOMETHING_TO_COMMIT" -eq "" ] ; then
。似乎[ "$SOMETHING_TO_COMMIT" -eq "0" ]
或[ "$SOMETHING_TO_COMMIT" -eq "" ]
应生成整数。
如何解决这个问题?
答案 0 :(得分:3)
您根本不需要将退出代码存储在变量中。如果git diff
在失败时返回非零退出代码(如最常见的Linux / Unix命令),则可以直接在if条件中使用它
if ! git diff --exit-code &>/dev/null ; then
echo "NOTHING TO COMMIT FOR $SOURCE_PATH";
如果!
不成功并且没有提交更改,则git diff
运算符会断言if条件 。此外,您应该更改脚本以在if条件下断言为true,并在else部分上将其作为
if git diff --exit-code &>/dev/null ; then
echo "COMMIT FOR ${SOURCE_PATH}"
git -C "$DIR/${SOURCE_PATH}" commit -F "${COMMIT_MESSAGE_FILE}"
else
echo "NOTHING TO COMMIT FOR ${SOURCE_PATH}";
fi
使其更具可读性和效率。
答案 1 :(得分:1)
第二个测试将变量与空字符串(“”)进行比较,但是使用-eq仅用于整数,因此您应该将其更改为=运算符:
if [ "$SOMETHING_TO_COMMIT" -eq "0" ] || [ "$SOMETHING_TO_COMMIT" = "" ] ; then
答案 2 :(得分:1)
在两个当前答案之间,您可以意识到您不必对SOMETHING_TO_COMMIT
进行条件分配。只需将退出状态(零或不归零)分配给参数;然后保证有一些非空整数值。
git diff --exit-code &>/dev/null; SOMETHING_TO_COMMIT=$?
if [ "$SOMETHING_TO_COMMIT" -eq 0 ]; then
echo "NOTHING TO COMMIT FOR $SOURCE_PATH";
else
echo "COMMIT FOR $SOURCE_PATH"
git -C "$DIR/$SOURCE_PATH" commit -F ${COMMIT_MESSAGE_FILE}
fi
正如Inian指出的那样,如果你只想进行一次比较,则不需要保存退出状态。您可以使用git
命令本身作为if
条件。当您可能需要进行多个比较时,保存该值非常有用:
some_command; status=$?
if [ "$status" -eq 0 ]; then
...
elif [ "$status" -eq 1 ]; then
...
else
...
fi