How does shell eval work? -


so wrote script takes argument. argument denotes kind of tests run, either qa or dev. have script change value in properties file based on argument, originally:

dev="site1.com" qa="site2.com"  if [ $1 == "dev" ];     sed -i "s/site=.*/site=${dev}/g" myfile.properties else ... 

but, changed to:

dev="site1.com" qa="site2.com"  eval environment=\$$1 sed -i "s/site=.*/site=${environment}/g" myfile.properties 

which makes don't need if-else structure based on argument.

how work "eval environment = \$$1" makes "${environment}" "${dev}" if "dev" argument?

in other words, using dev argument (sh script.sh dev)
${environment} == ${dev} rather ${environment} == "dev"?

how eval work?

the basic way eval works arguments treated command line , command line re-evaluated. quotes re-interpreted; i/o redirection re-interpreted; variables re-interpreted.

given:

eval environment=\$$1 

the first pass through creates:

eval environment=$dev 

the eval interprets as

environment=site1.com 

problem in code in question

you don't put spaces around assignments in shell, in eval.

dev="site1.com" qa="site2.com"  eval environment=\$$1 sed -i "s/site=.*/site=${environment}/g" myfile.properties 

in bash, you'd use:

environment=${!1} 

this avoids explicit eval, dangerous if (ab)user typed sh yourscript '$(rm -fr $home &)' instead of sh yourscript dev. if use eval, had better validate evaluate.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -