Linux 意外标记“then”附近的语法错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20235217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Syntax error near unexpected token 'then'
提问by Amitābha
I typed the code the same as The Linux Command Line: A Complete Introduction, page 369 but prompt the error:
我输入的代码与The Linux Command Line: A Complete Introduction,第 369 页相同,但提示错误:
line 7 `if[ -e "$FILE" ]; then`
the code is like:
代码是这样的:
#!/bin/bash
#test file exists
FILE="1"
if[ -e "$FILE" ]; then
if[ -f "$FILE" ]; then
echo :"$FILE is a regular file"
fi
if[ -d "$FILE" ]; then
echo "$FILE is a directory"
fi
else
echo "$FILE does not exit"
exit 1
fi
exit
I want to realize what introduced the error? How can I modify the code? My system is Ubuntu.
我想知道是什么引入了错误?如何修改代码?我的系统是 Ubuntu。
采纳答案by janos
There must be a space between if
and [
, like this:
if
和之间必须有一个空格[
,如下所示:
#!/bin/bash
#test file exists
FILE="1"
if [ -e "$FILE" ]; then
if [ -f "$FILE" ]; then
echo :"$FILE is a regular file"
fi
...
These (and their combinations) would all be incorrecttoo:
这些(及其组合)也都是不正确的:
if [-e "$FILE" ]; then
if [ -e"$FILE" ]; then
if [ -e "$FILE"]; then
These on the other hand are all ok:
另一方面,这些都可以:
if [ -e "$FILE" ];then # no spaces around ;
if [ -e "$FILE" ] ; then # 1 or more spaces are ok
Btw these are equivalent:
顺便说一句,这些是等效的:
if [ -e "$FILE" ]; then
if test -e "$FILE"; then
These are also equivalent:
这些也是等价的:
if [ -e "$FILE" ]; then echo exists; fi
[ -e "$FILE" ] && echo exists
test -e "$FILE" && echo exists
And, the middle part of your script would have been better with an elif
like this:
而且,脚本的中间部分会更好elif
:
if [ -f "$FILE" ]; then
echo $FILE is a regular file
elif [ -d "$FILE" ]; then
echo $FILE is a directory
fi
(I also dropped the quotes in the echo
, as in this example they are unnecessary)
(我也去掉了 中的引号echo
,因为在这个例子中它们是不必要的)
回答by Sarath
The solution is pretty simple. Just give space between if and the opening square braces like given below.
解决方案非常简单。只需在 if 和左方括号之间留出空间,如下所示。
if [ -f "$File" ]; then
<code>
fi
if [ -f "$File" ]; then
<code>
fi