Thanks. I found myself wanting to use eval today, because I was trying to build up a complicated docker-compose command depending on certain flags. First I tried doing
docker-compose \
-f x.yml \
if [ -n $BLA ]; then
-f y.yml \
fi
;
But this didn’t work, because bash doesn’t work like an html templating language. So I built up the string and then tried to execute the comnand in backticks, but that swallowed the stdout from my docker containers:
CMD="docker compose"
CMD="${CMD} -f x.yml"
if [ -n $BLA ]; then
CMD="${CMD} -f y.yml"
fi `$CMD`
Then I googledexec
.. that looked a bit too hardcore — I didn’t need to replace the parent process. Then I googled eval
and that looked like what I wanted, which did indeed work:
CMD="docker compose"
CMD="${CMD} -f x.yml"
if [ -n $BLA ]; then
CMD="${CMD} -f y.yml"
fi eval "$CMD"
But your article also came up in the results, and although I have no intention of allowing user input here, you inspired me to see if I could do this without eval
and sure I can!
ARGS="-f x.yml"
if [ -n $BLA ]; then
ARGS="${ARGS} -f y.yml"
fidocker-compose $ARGS
Thanks for inspiring me to do better!