Hi,
I have a shell script where I have to connect t oracle database. I have to store the command in a variable and then run the command through the variable.The OS is solaris 10 and the shell is bash.pls help when I run the command it doesnot work.Thanks.
if [db=prod]
CONNECT= "sqlplus ser/password@dbname"
elif [db=test]
CONNECT= "sqlplus ser/password@dbname"
else
exit
fi
'CONNECT'
if [ "$db" = "$prod" ]
then
CONNECT="sqlplus ser/password@dbname"
elif [ "$db" = "$test" ]
then
CONNECT="sqlplus ser/password@dbname"
else
exit
fi
$CONNECT
Hi thanks a lot . It worked , I have another problem as when I am redirecting the output to a file it doesn't connect to database.Pls suggest.thanks in advance
if [ "$db" = "$prod" ]
then
CONNECT="sqlplus ser/password@dbname <<END_SQL > logfile1
elif [ "$db" = "$test" ]
then
CONNECT="sqlplus ser/password@dbname"<<END_SQL > logfile2
else
exit
fi
$CONNECT]
sql statements
quit ;
END_SQL
exit
This question made me worry when I saw it, and that's why -- take it to its natural conclusion and it stops working. Shell doesn't work that way... It will split spaces, but it won't start over from scratch and assume that everything in your string is shell syntax. That'd be dangerous, and if you want dangerous, you have to use eval to forcefeed it to the shell. That'll ensure that a string containing <<EOF, >redirection, any accidental spaces and quotes, and/or `rm -Rf ~/` will be processed as the shell literally would instead of fixed string contents.
So the answer, the real answer, is "don't do that". Otherwise, 6 months down the road, you're going to try and read your own code and have no idea what its doing because commands are defined 3 if-statements deep, 9 pages away from where they're used, and run via recursive recursive eval. It'll be your job to figure out what elusive injected quote, brace, bracket, backtick, or dollar sign is making your generated-code-generator explode and fix it -- or more likely give it a proper rewrite into this:
if [ somecondition ]
then
LOGFILE="logfile1"
AUTH="ser/password@dbname"
else
LOGFILE="logfile2"
AUTH="ser/password@dbname"
fi
sqlplus $AUTH <<END_SQL > $LOGFILE
...
quit;
END_SQL
Don't use variables to store commands. The shell has to do a lot of doublethink to handle that and is left open to lots of bugs and mistakes you'd be better off avoiding. Use variables to store the parts of the command that vary.
Thanks a lot. Not only you solved my problem but also showed me the better way to do it. Very very thankful. Not to mention your explanation was great.:)