Created
February 15, 2023 20:28
-
-
Save tsharley/37d91906cdd51e05a0a7cc14bfd6cf2e to your computer and use it in GitHub Desktop.
Heredoc script to generate bash code / another script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # generate-script.sh | |
| # A script that generates another script using a heredoc. | |
| # More examples and use cases at https://tldp.org/LDP/abs/html/here-docs.html. | |
| # Based on an idea by Albert Reiner. | |
| OUTFILE=generated.sh # Name of the file to generate. | |
| # ----------------------------------------------------------- | |
| # 'Here document containing the body of the generated script. | |
| ( | |
| cat <<'EOF' | |
| #!/bin/bash | |
| echo "This is a generated shell script." | |
| # Note that since we are inside a subshell, | |
| #+ we can't access variables in the "outside" script. | |
| echo "Generated file will be named: $OUTFILE" | |
| # Above line will not work as normally expected | |
| #+ because parameter expansion has been disabled. | |
| # Instead, the result is literal output. | |
| a=7 | |
| b=3 | |
| let "c = $a * $b" | |
| echo "c = $c" | |
| exit 0 | |
| EOF | |
| ) > $OUTFILE | |
| # ----------------------------------------------------------- | |
| # Quoting the 'limit string' prevents variable expansion | |
| # within the body of the above 'here document.' | |
| # This permits outputting literal strings in the output file. | |
| if [ -f "$OUTFILE" ] | |
| then | |
| chmod 755 $OUTFILE | |
| # Make the generated file executable. | |
| else | |
| echo "Problem in creating file: \"$OUTFILE\"" | |
| fi | |
| # This method also works for generating | |
| #+ C programs, Perl programs, Python programs, Makefiles, | |
| #+ and the like. | |
| exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment