1

Assume two files: file1 and file2. file1 is a short Bash script, that references file2 in order to obtain a text string. The text string includes a variable name ($VAR1), but the variable itself is assigned a value in file1.

$ cat file1
#!/bin/bash
VAR1="World"
CMDS=$(cat file2)
echo "$CMDS"

$ cat file2
Hello $VAR1 !

Under the above setup, the variable name is not recognized correctly during the execution of file1.

$ bash file1 
Hello $VAR1 !

What do I need to do so that the variable name is recognized correctly during the execution of file1?

3
  • 2
    Why do you want to do this? Commented Oct 17, 2017 at 11:02
  • @123 Apparently, he wants to use bash as a templating system. Commented Oct 17, 2017 at 11:23
  • @chepner Very odd way to approach templating. Commented Oct 17, 2017 at 11:29

1 Answer 1

0

As you do not execute file2, just cat its content, the variable in file2 only serves as a placeholder. You could pipe the output from cat to sed, like so:

CMDS=$(cat file2|sed -e "s/\$VAR1/$VAR1/")
Sign up to request clarification or add additional context in comments.

1 Comment

sed knows how to read file2. The cat is useless.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.