Search code examples
bashwhile-loopcommand-substitution

Command with input redirection inside while loop


I am trying to loop inside a text file containing commands to be executed:

    while IFS= read -r line
    do
      $line
    done < msmtp-cmds.txt

The commands inside the text file are:

  msmtp -t < message1.txt
  msmtp -t < message2.txt

After command substitutions the redirection sign seems to be ignored, as msmtp is trying to use message1.txt as a recipient, but I cannot figure why


Solution

  • < is not an argument to the command; it's shell syntax that is parsed before parameter expansion. If your intent is to execute arbitrary code read from a file, that's what eval is for.

    while IFS= read -r line; do
      eval "$line"
    done < msmtp-cmds.txt
    

    However, at that point, you may as well just source the file rather than reading it line by line:

    . smtp-cmds.txt