Problem with heredoc inside case. Bash script [duplicate]

Deadly 提交于 2020-07-22 14:13:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!