Home > Back-end >  How to execute a test as part of bash string as executable command?
How to execute a test as part of bash string as executable command?

Time:04-17

If I have a "file" that includes...

rm -rf /etc/motd
if [ -f /etc/motd]; then rm -rf /etc/motd; fi

And I try to do...

while read -r line 
do 
  command ${line}
  #$(${line})
  #eval ${line}
done< "file"

The 1st line runs of course. But the 2nd command fails with if : command not found. Which I understand the error because not an explicit command. So the question is how to execute a test as part of a string as bash script logic? I tried eval, and $(), i.e. subshells, but still errors out? Tripping over the 'if' test. I need a conditional test before the command/script code is executed in a one-liner. There has to be a way to do this, right?

CodePudding user response:

If your intention is to load and execute "file" from another script just do

source "file"

no need to loop over the lines.

  •  Tags:  
  • bash
  • Related