How to expand shell variables in a text file?

前端 未结 10 1446
夕颜
夕颜 2021-02-04 02:05

Consider a ASCII text file (lets say it contains code of a non-shell scripting language):

Text_File.msh:

spool on to \'$LOG_FILE_PATH/lo         


        
10条回答
  •  不知归路
    2021-02-04 02:29

    One limitation of the above answers is that they both require the variables to be exported to the environment. Here's what i came up with that would allow the variables to be local to the current shell script:

    #!/bin/sh
    FOO=bar;
    FILE=`mktemp`; # Let the shell create a temporary file
    trap 'rm -f $FILE' 0 1 2 3 15;   # Clean up the temporary file 
    
    (
      echo 'cat < $FILE
    . $FILE
    

    The above example allows the variable $FOO to be substituted in the files named on the command line. I'm sure it can be improved, but this works for me so far.

    Thanks to both previous answers for their ideas!

提交回复
热议问题