1

I am trying to check whether a directory already exists or not inside a case-control statement. But it is giving an error in 'then' statement.

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'
1
  • 2
    ShellCheck automatically points out common problems like these Commented Mar 21, 2020 at 18:08

1 Answer 1

2

The parser is seeing then outside of an if statement, because you don't have the keyword if in a command position. You have the word if[-d which the parser accepts as an ordinary command name; 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:

if test -d "$dname"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.