Syntax error near unexpected token 'then'

The solution is pretty simple. Just give space between if and the opening square braces like given below.

if [ -f "$File" ]; then <code> fi


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

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:

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)

Tags:

Linux

Unix

Shell