0

I have a bash script that contains a variable. In the same script, I have an HTML section that, for now, outputs "Hello".

I'd like the HTML section of the bash script to retrieve a variable, and display that in the same heading as the "Hello" section. Essentially, the output on the HTML page should be something like this "Hello Adam".

For now, as simple as it gets, my bash script code is as follows:

#!/bin/bash

firstname="Adam"

echo $firstname

cat << _EOF_
<!DOCTYPE html>
<html>
<body>

<h1>Hello</h1>

</body>
</html>

_EOF_

How do I get the variable in the HTML section so that it can display the $firstname variable?

For reference, I currently run the script using git-bash by executing sh {name-of-script} > test.html

5
  • 3
    You write $firstname in the here doc... Commented Jul 22, 2019 at 16:33
  • @thatotherguy sorry what do you mean? Commented Jul 22, 2019 at 16:34
  • 2
    <h1>Hello $firstname</h1> Commented Jul 22, 2019 at 16:34
  • I feel very stupid! That works. If you want to put your answer as an answer to the question rather than a comment, I'll accept it :) Thanks! Commented Jul 22, 2019 at 16:35
  • 3
    Side note: if you use sh myscript, you'll run into problems when using Bash specific features such as arrays. You might not even actually run Bash (on Ubuntu, /bin/sh is Dash). To avoid that and let the script use the interpreter specified in the shebang line, make it executable and run it with ./myscript instead. Commented Jul 22, 2019 at 16:46

1 Answer 1

2

You can use regular variable expansion in unquoted here documents:

# Hello Adam
firstname="Adam"
cat << EOF
Hello $firstname
EOF

If you want certain values to not be expanded, escape them:

# $firstname is Adam
cat << EOF
\$firstname is $firstname
EOF

If you don't want any values to be expanded, quote the delimiter:

# $firstname is not expanded in quoted heredocs
cat << "EOF"
$firstname is not expanded in quoted heredocs
EOF
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.