案例中的 heredoc 有问题。 Bash 脚本

Problem with heredoc inside case. Bash script

如果在我的终端我写

cat <<-EOF
hello
EOF

我得到了预期的输出,你好。

现在,在我正在编写的脚本中我有

PARAMS=""
while (( "$#" )); do
  case "" in
    -h|--help)
      cat <<-EOF
      hello
      EOF
      exit 0  
      ;;
    --) # end argument parsing
      shift
      ...

但是 vscode 突出显示行 cat<<-EOF 之后的所有内容,就好像它们都是字符串一样,基本上忽略了 EOF。 事实上,当我 运行 脚本时,我得到

syntax error: unexpected end of file

错误

编辑:

如果我这样缩进代码:

while (( "$#" )); do
  case "" in
    -h|--help)
      cat <<EOF
      ciao
EOF
      exit 0  
      ;;
    --) # end argument parsing
      shift
      ...

左边有 EOF,vscode 会按应有的方式识别它,将文件的其余部分高亮显示为正常的 bash 脚本,一切正常。但是在缩进方面这很糟糕。有没有办法用 cat 命令缩进 EOF?

-EOF 必须在行首。当我漂亮地打印脚本并无意中缩进 heredoc 终止符时,我犯了好几次这个错误。

您可以像这样在 here-doc 中的 EOF 之前使用空格:

    cat <<"    EOF"
        foo
        bar
    EOF

但为了避免 formatting/indentation 问题,我更喜欢为此使用函数:

print_help() {
cat <<EOF
    foo
    bar
EOF
}
...
PARAMS=""
while (( "$#" )); do
  case "" in
    -h|--help)
      print_help
      exit 0  
      ;;
    --) # end argument parsing
      shift
      ...

它还使代码更清晰。