Search code examples
bashshellunixsolarisksh

How to expand shell variables in a text file?


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/logfile.log';
login 'username' 'password';
....

Now if this were a shell script I could run it as $ sh Text_File.msh and the shell would automatically expand the variables. What I want to do is have shell expand these variables and then create a new file as Text_File_expanded.msh as follows:

Text_File_expanded.msh:

spool on to '/expanded/path/of/the/log/file/../logfile.log';
login 'username' 'password';
....

Consider:

$ a=123
$ echo "$a"
123

So technically this should do the trick:

$ echo "`cat Text_File.msh`" > Text_File_expanded.msh

...but it doesn't work as expected and the output-file while is identical to the source.

So I am unsure how to achieve this.. My goal is make it easier to maintain the directory paths embedded within my non-shell scripts. These scripts cannot contain any UNIX code as it is not compiled by the UNIX shell.


Solution

  • This solution is not elegant, but it works. Create a script call shell_expansion.sh:

    echo 'cat <<END_OF_TEXT' >  temp.sh
    cat "$1"                 >> temp.sh
    echo 'END_OF_TEXT'       >> temp.sh
    bash temp.sh >> "$2"
    rm temp.sh
    

    You can then invoke this script as followed:

    bash shell_expansion.sh Text_File.msh Text_File_expanded.msh