Shell Script – syntax error near unexpected token `else’ Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Shell Script – syntax error near unexpected token `else’ without wasting too much if your time.

The question is published on by Tutorial Guruji team.

With the following shell script, why I am getting errors

syntax error near unexpected token `else'

Shell Script

echo "please enter username"
read user_name
echo "please enter password"
read -s pass
echo ${ORACLE_SID}
SID=${ORACLE_SID}
if ["${ORACLE_SID}" != 'Test'] then
sqlplus -s -l $USER_NAME/$PASS@$SID <<EOF
copy from scott/tiger@orcl insert EMP using select * from EMP
exit
EOF
else
echo "Cannot copy"
fi

Answer

You have to terminate the condition of if like this:

if [ "${ORACLE_SID}" != 'Test' ]; then

or like this:

if [ "${ORACLE_SID}" != 'Test' ]
then

Note: you also have to put spaces after [ and before ].

The reason for the ; or linebreak is that the condition part of the if statement is just a command. Any command of any length to be precise. The shell executes that command, examines the exit status of the command, and then decides whether to execute the then part or the else part.

Because the command can be of any length there needs to be a marker to mark the end of the condition part. That is the ; or the newline, followed by then.

The reason for the spaces after [ is because [ is a command. Usually a builtin of the shell. The shell executes the command [ with the rest as parameters, including the ] as mandatory last parameter. If you do not put a space after [ the shell will try to execute [whatever as command and fail.

The reason for space before the ] is similar. Because otherwise it will not be recognized as a parameter of its own.

We are here to answer your question about Shell Script – syntax error near unexpected token `else’ - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji