#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2008
    Posts
    22
    Rep Power
    0

    Syntax error in If loop


    I have a requirement to check the following conditions..

    If my folders are not A and B then list files in the directory else no listing the files

    so my if loop is some thing like this.

    Code:
    if [ $dirName = "C" && $dirName \!= "A" && \!= "B" ] then
    ls -la
    else
    echo "Inside else loop"
    fi
    But upon executing I am getting the below error..

    Code:
    ./application/root/shellscript/Test.sh: line 5: [: missing `]'
    Please help me..if there is any thing wrong in the syntax
  2. #2
  3. kill 9, $$;
    Devshed Supreme Being (6500+ posts)

    Join Date
    Sep 2001
    Location
    Shanghai, An tSín
    Posts
    6,898
    Rep Power
    3887
    You have a few issues with this code (assuming you're using bash - you haven't said): firstly, an "if" statement is not a loop - it only executes once ("while" and "for" are loops because keep looping over the same code multiple times).

    Here it is cleaned up:
    Code:
    #!/bin/bash
    dirName='A';
    if [ $dirName = "C" ] && [ $dirName != "A" ] && [ $dirName != "B" ]; then
       ls -la
    else
       echo "Inside else statement"
    fi
    - You need to have square brackets around each of the conditions you're testing for
    - You don't need to escape the !=
    - You need to specify $dirName every time you do a comparison
    - You need semicolon before "then"
    - I haven't fixed the logical problem here: if $dirName = "C" then you're already guaranteed that it isn't equal to "A" or "B".

IMN logo majestic logo threadwatch logo seochat tools logo