Home > Software design >  Bash: command substitution when reading from a file
Bash: command substitution when reading from a file

Time:09-28

Not sure if I am being dumb here but I am not able to figure this out.

If I put this in bash script:

var="`date ' %a %b %d'`*.*INFO Ended execution of script"
echo $var

The output that I get is:

Mon Sep 27*.*INFO Ended execution of script

However, If I put the same content in a file:

"`date ' %a %b %d'`*.*INFO Ended execution of script"

And then write a small bash script to read the content of this file

while read -e line
do
        echo "$line"
done < file

When I execute this script I get

"`date ' %a %b %d'`*.*INFO Ended execution of script"

How do i get the command substitution to work when I read the content from a file?

CodePudding user response:

To be clear, this is an extremely bad idea, and is not something you should ever actually do. However, it would look like:

while IFS= read -r line; do
  eval "echo $line"           ## DANGEROUS: Do not do this!
done

In terms of why it's a bad idea:

  • It's innately insecure. BashFAQ #48 goes into more details on that, but in short, if your data can run the date command, it can run any other command as well.
  • It's slow. $(date) starts a new copy of /usr/bin/date each time it's run. Using printf -v date '%(%a %b %d)T' -1 stores the date formatted the way you want in $date far faster.
  • Related