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/[email protected]$SID <<EOF copy from scott/[email protected] 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.