Search code examples
stringbashif-statementevaluate

bash evaluate if statement from string


I have a file which contains shell test statements.

I need to evaluate the expression. For example:

a="something"
fromfile='[ "$a" == "something" ]'

if `$fromfile`; then
  echo "true"
else
  echo "false"
fi

It always throws false. I tried with `` and eval, but still not works.

What is the solution?


Solution

  • I guess you just didn't hit the right syntax. You really need eval for this:

    a="something"
    fromfile='[ "$a" = "something" ]'
    if eval "$fromfile"
    then
      echo "true"
    else
      echo "false"
    fi
    

    But please read about the dangers eval imposes on the security side! If you plan to execute strings you are given, if only in part, (by the user, from a data base, from a web site, ...) you might introduce a security risk. (Consider fromfile='rm -rf ~'In case you don't understand this: don't try this! It will remove everything from your home directory!)

    There are better options in most cases like declaring shell functions and passing their names instead of a complete syntax-containing string.