0

Here is my shell script and the error I get when running it:

#!/bin/bash

path=$1
execute=$2
a=$3
operation=$4
name=$5

if [ "$operation" == "run" ]; then
    cd $path
   ./$execute $a 
fi
elif [ "$operation" == "copy" ]; then
    mkdir -p $path
    cp $execute $path/$name 
fi
elif [ "$operation" == "delete" ]; then
     rm $path
     cd copy
     rm $name
     cd ..
     rmdir copy
fi
./commandsScript.sh: line 14: syntax error near unexpected token `elif'
./commandsScript.sh: line 14: `elif [ "$operation" == "copy" ]; then'

I've spent a long time trying all sort if-else statements variances but have not found the error solution. May someone help?

2 Answers 2

4

Consider using a case expression instead of a set of chained if statements:

case "$operation" in
run)
    cd "$path"
    ./"$execute" "$a"
    ;; 
copy)
    mkdir -p "$path"
    cp "$execute" "$path/$name"
    ;;
delete)
    rm "$path"
    cd copy
    rm "$name"
    cd ..
    rmdir copy
    ;;
esac

I've also taken the liberty to quote all of your parameter expansions, which is what you should get into the habit of doing to make your script robust against arguments/variables with embedded whitespace.

Also, I would advise investing in proper error handling.

Sign up to request clarification or add additional context in comments.

Comments

4

Remove the first and second fi. It should look like

if ...
...
elif ...
...
elif ...
...
fi

See Bash - Conditional Constructs for more details.

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.