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

如何解决Linux If-Else语句语法错误?,linux,bash,if-statement,Linux,Bash,If Statement,我试图检查case-control语句中是否已经存在一个目录。但它在'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 creat

我试图检查case-control语句中是否已经存在一个目录。但它在'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
  ;;
错误消息:

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

解析器在
if
语句之外看到
then
,因为在命令位置没有关键字
if
。您有一个单词
if[-d
,解析器将其作为普通命令名接受;解析器不知道或不关心该命令是否实际存在

空格很重要:

if [ -d "$dname" ]
括号本应提醒您语法,但可能造成了比以往任何时候都要多的麻烦。
[
是命令,它需要
]
作为其最终参数。使用名称
test
简单得多,不会让您误以为括号对解析器有某种特殊性:

if test -d "$dname"
自动指出这些常见问题