我有一个小的bash脚本:
#!/bin/bash
if [[ "$@" == "pull" ]]
then
# stuff
elif [[ "$@" == "push" ]]
then
# stuff
else
echo "Command not recognised"
fi
它位于/usr/bin/local 中,我让它可执行。但是每当我运行它时,我都会script:1: == not found
有什么想法吗?
如果这很重要,这就是macOS。
-
不要使用
[[
,不是由 POSIX 定义的。而是使用[
-
不要使用
==
,使用=
-
不要使用
$@
,使用$1
-
在这种情况下不要使用双引号表示
pull
和push
,事实上根本不使用它们 -
当sh会做时不要使用Bash
。
更新的脚本:
#!/bin/sh
if [ "$1" = pull ]
then
# stuff
elif [ "$1" = push ]
then
# stuff
else
echo 'Command not recognised'
fi
作为您的解释器,您唯一的问题是您对 "$@"
的使用,在 bash 的 [[
和 POSIX 的 [
和 test
等测试中,它扩展到所有用引号括起来的参数(就像"$*"
一样)。 您可能希望"$1"
只测试第一个参数。
您还可以考虑使用 case
(开关)语句:
#!/bin/bash
case "$1" in
( pull ) echo "you said pull" ;;
( push ) echo "you said push" ;;
( * ) echo "Command '$1' is not recognised" ;;
esac
(上面的代码将在 bash、sh 和 zsh 中工作。 我假设由于代码的其他方面,您仍然需要 bash。