5

Assuming I have a variable v="c d e f g" and a file with the content:

line1
$v
line3

How can I make a bash script print this file with the content of the variable in line 2 as if I was using a here-document like this:

#!/bin/bash

v="c d e f g"

cat << EOF
line1
$v
line3
EOF

Output:

line1
c d e f g
line3

1 Answer 1

10

Using envsubst to parse the file and replace the variables that corresponds to environment variables (in envsubst's environment):

$ v='c d e f g'
$ v=$v envsubst <file
line1
c d e f g
line3

Or, by exporting v first:

$ export v
$ envsubst <file
line1
c d e f g
line3

On my system, envsubst is distributed as part of the gettext package.

3
  • Or do an explicit sed replacement... Commented Mar 30, 2024 at 4:16
  • 1
    @keshlam Assuming you don't know the value of the variable (it may be user input, for example), that may be impossible. If you use $v in the replacement text of a substitution comman in sed, it restricts the set of characters the variable can contain. It may , for example, not contain "&", or "\" followed by a digit, or the character that is used as delimiter in the substitution command. Depending on the sed implementation, you may even introduce a serious code injection vulnerability. Commented Mar 30, 2024 at 6:07
  • Granted, but (1) that isn't always a concern, (2) that ca Commented Mar 30, 2024 at 13:21

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.