Syntax error near unexpected token 'then'

后端 未结 2 763
情话喂你
情话喂你 2020-12-03 13:11

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`
相关标签:
2条回答
  • 2020-12-03 13:43

    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)

    0 讨论(0)
  • 2020-12-03 14:05

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

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

    0 讨论(0)
提交回复
热议问题