简体   繁体   中英

How do I execute SQL in a loop within a bash script?

I've got a problem with a bash script in which I'd like to execute SQL.
As an example if I simply write :

sqlplus -s << EOF
${USER}/${PASSWD}@DataBase
show user;
exit;

it works.
But as soon as I put it into a loop it doesn't work anymore.
For example :

while (condition)
do 
   echo $ANSWER         
   read -p '[y/n]' ANSWER  
   echo $ANSWER  
   if [ $ANSWER = 'y' ]  
   then  
        sqlplus -s << EOF  
        ${USER}/${PASSWD}@DataBase  
        show user;  
        exit;
        EOF
        break  
   elif [ $ANSWER = 'n' ]  
   then  
        break  
   fi
done
echo $ANSWER

And the results I've got is : line 26: syntax error : unexpected end of file
(knowing that the line "echo $ANSWER" is the line 25...)

If anyone has an idea about why it doesn't want to work I will be really thankful for the help !

Your problem is that the shell expects the delimiter for the here document at the beginning of the line. Your EOF is in the middle of the line, and therefore it isn't recognized as a delimiter anymore.

This works as expected:

while (true)
do 
   echo $ANSWER         
   read -p '[y/n]' ANSWER  
   echo $ANSWER  
   if [ $ANSWER = 'y' ]  
   then  
        sqlplus -s << EOF  
        ${USER}/${PASSWD}@DataBase  
        show user;  
        exit;
EOF
        break  
   elif [ $ANSWER = 'n' ]  
   then  
        break  
   fi
done
echo $ANSWER

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM