简体   繁体   English

如何解决 Linux If-Else 语句语法错误?

[英]How to solve Linux If-Else statement syntax error?

I am trying to check whether a directory already exists or not inside a case-control statement.我试图检查一个目录是否已经存在于 case-control 语句中。 But it is giving an error in 'then' statement.但它在“then”语句中给出了错误。

case $choice in
1)echo "Enter directory name: "
  read dname
  mkdir $dname
  if[-d "$dname"]
  then
     echo "$dname directory already exists."
  else
     echo "$dname directory successfully created."
  fi
  read
  ;;

error message:错误信息:

uan.sh: line 13: syntax error near unexpected token `then'
uan.sh: line 13: `  then'

The parser is seeing then outside of an if statement, because you don't have the keyword if in a command position.解析器在if语句之外看到then ,因为在命令位置没有关键字if You have the word if[-d which the parser accepts as an ordinary command name;你有if[-d这个词,解析器接受它作为一个普通的命令名称; the parser doesn't know or care whether the command actually exists or not.解析器不知道或不关心命令是否实际存在。

Whitespace is important:空格很重要:

if [ -d "$dname" ]

The brackets are supposed to remind you of syntax, but have probably caused more trouble than they have ever saved.括号应该提醒您语法,但可能造成的麻烦比它们保存的要多。 [ is the command, and it requires ] as its final argument. [是命令,它需要]作为它的最后一个参数。 Using the name test is much simpler and doesn't lull you into thinking the brackets are somehow special to the parser:使用名称test要简单得多,并且不会让您认为括号对解析器来说有些特殊:

if test -d "$dname"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM