[: missing `]' in bash script

夙愿已清 提交于 2019-11-27 08:45:43

问题


So I'm writing a bash shell script, and my first few lines looks like this:

if ! [ $# -eq 0 || $# -eq 1 ]; then
    echo -e "Usage: myScriptName [\e[3mdir\e[0m] [\e[3m-f file\e[0m]"
    exit 1
fi

But when I run it, it says "[: missing `]'". I don't see a missing ], and nothing except the ; is touching the ], so what am I missing?


回答1:


You cannot use operators like || within single-brace test expressions. You must either do

! [[ $# -eq 0 || $# -eq 1 ]]

or

! { [ $# -eq 0 ] || [ $# -eq 1 ]; }

or

! [ $# -eq 0 -o $# -eq 1 ]

The double-brace keyword is a bash expression, and will not work with other POSIX shells, but it has some benefits, as well, such as being able to do these kinds of operations more readably.

Of course, there are a lot of ways to test the number of arguments passed. The mere existence of $2 will answer your question, as well.



来源:https://stackoverflow.com/questions/35281797/missing-in-bash-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!