问题
If in my terminal I write
cat <<-EOF
hello
EOF
I get the expected output, hello.
Now, In a script I'm writing I have
PARAMS=""
while (( "$#" )); do
case "$1" in
-h|--help)
cat <<-EOF
hello
EOF
exit 0
;;
--) # end argument parsing
shift
...
But vscode is highlighting everything after the line cat<<-EOF
as if it all was a string, basically ignoring the EOF.
And in fact when I run the script I get a
syntax error: unexpected end of file
error
Edit:
if I indent the code like this:
while (( "$#" )); do
case "$1" in
-h|--help)
cat <<EOF
ciao
EOF
exit 0
;;
--) # end argument parsing
shift
...
with EOF on the left, vscode recognises it as it should, hilighting the rest of the file as a normal bash script and everithing works. But indentation-wise this sucks. Is there a way to indent EOF with the cat command?
回答1:
The -EOF has to be at the beginning of the line. I've made that mistake several times when I prettyprint a script and inadvertently indent the heredoc terminator.
回答2:
You could to use spaces before EOF
in here-doc like this:
cat <<" EOF"
foo
bar
EOF
But to avoid formatting/indentation issues I prefer to use functions for that:
print_help() {
cat <<EOF
foo
bar
EOF
}
...
PARAMS=""
while (( "$#" )); do
case "$1" in
-h|--help)
print_help
exit 0
;;
--) # end argument parsing
shift
...
It also makes code cleaner.
来源:https://stackoverflow.com/questions/61308141/problem-with-heredoc-inside-case-bash-script