0

This is my code:

 #!/bin/bash

if [[ -z $1 ]]; then
        echo "No arguments passed: valid usage is script.sh filename"
else if [[ ! -f "$1" ]]; then
        echo "file does not exists"
else
        for i in {558..2005};
        do
                if [[ ! -d "/abc" ]]; then
                        mkdir /abc
                fi
                mkdir /abc/xyz$i
                cp $1 /abc/xyz$i/$1
        done
fi

my error: can anyone please help me i do not know what to do? I do not know where I am making mistake?

./script.sh: line 17: syntax error: unexpected end of file 
5
  • 2
    Use elif not else if. Commented Jun 25, 2020 at 17:50
  • 1
    Try out shellcheck. It helpfully says "Use 'elif' instead of 'else if' (or put 'if' on new line if nesting)." Commented Jun 25, 2020 at 17:51
  • Thanks That Worked for me Commented Jun 25, 2020 at 17:51
  • I'm not able to find any duplicates for this issue. @MichalH do you want to post that as an answer? Commented Jun 25, 2020 at 17:55
  • stackoverflow.com/questions/7126752/… is sorta' a duplicate, insofar as it asks the differences between the forms, and the answer (correctly) states that an extra fi is required when using else if instead of elif; communicating that difference does answer this question. Commented Jun 25, 2020 at 17:59

2 Answers 2

2

Use elif instead of else if.

Syntax of if in bash:

if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi
Sign up to request clarification or add additional context in comments.

Comments

2

Instead of a single if statement with an elif clause, you nested a second if statement in the else clause of the first, but only terminated the second one. Your code, reformatted to highlight the issue, is

if [[ -z $1 ]]; then
    echo "No arguments passed: valid usage is script.sh filename"
else
    if [[ ! -f "$1" ]]; then
        echo "file does not exists"
    else
        for i in {558..2005};
        do
            if [[ ! -d "/abc" ]]; then
                mkdir /abc
            fi
            mkdir /abc/xyz$i
            cp $1 /abc/xyz$i/$1
        done
    fi

Notice the lack of a second fi which would terminate the outer if statement.

Using elif, your code becomes

if [[ -z $1 ]]; then
    echo "No arguments passed: valid usage is script.sh filename"
elif [[ ! -f "$1" ]]; then
    echo "file does not exists"
else
    for i in {558..2005};
    do
        if [[ ! -d "/abc" ]]; then
            mkdir /abc
        fi
        mkdir /abc/xyz$i
        cp $1 /abc/xyz$i/$1
    done
fi

The elif clause doesn't require a closing fi; it is implicitly terminated by the following else clause.

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.