意外标记“then"附近的语法错误 [英] Syntax error near unexpected token 'then'
问题描述
我输入的代码与 Linux 命令行相同:完整介绍,第 369 页但是提示错误:
I typed the code the same as The Linux Command Line: A Complete Introduction, page 369 but prompt the error:
line 7 `if[ -e "$FILE" ]; then`
代码如下:
#!/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
我想弄清楚是什么引入了错误.如何修改代码?我的系统是 Ubuntu.
I want to figure out what introduced the error. How can I modify the code? My system is Ubuntu.
推荐答案
if
和 [
之间必须有一个空格,像这样:
There must be a space between if
and [
, like this:
#!/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 incorrect too:
if [-e "$FILE" ]; then
if [ -e"$FILE" ]; then
if [ -e "$FILE"]; then
另一方面这些都可以:
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
这些也是等价的:
if [ -e "$FILE" ]; then echo exists; fi
[ -e "$FILE" ] && echo exists
test -e "$FILE" && echo exists
而且,使用这样的 elif
会更好地编写脚本的中间部分:
And, the middle part of your script would have been better with an elif
like this:
if [ -f "$FILE" ]; then
echo $FILE is a regular file
elif [ -d "$FILE" ]; then
echo $FILE is a directory
fi
(我也去掉了 echo
中的引号,因为在这个例子中它们是不必要的)
(I also dropped the quotes in the echo
, as in this example they are unnecessary)
这篇关于意外标记“then"附近的语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!