MacBook 上的 Bash HereDoc 变量出现换行符错误

问题描述 投票:0回答:1

我有一个脚本可以在 Ubuntu 22.04 上使用 Bash 愉快地运行。但是,在 Arm MacBook 上的 bash (v 5.2) 下执行相同的脚本时开始出现错误。

下面是脚本中有问题的部分:

my_script=$(cat <<EOF
while getopts \":lr:e:\" option; do \n
  case \\\${option} in \n
     l) \n
        cat file.txt \n
        exit;; \n
     e) \n
        vi file.txt \n
        exit;; \n
     r)  \nB
         rm file.txt \n
        exit;; \n
\n
     *) \n
       echo \"invalid option. \" \n
     exit;; \n
  esac \n
done \n

EOF
)

计划是将此变量作为独立脚本转储到文件中,因此它应该保留格式,但是,我遇到了以下错误:

syntax error near unexpected token `;;'

有人可以建议为什么 bash 会抱怨这个吗? 这就是我将脚本写入文件的方式:

printf \"${my_script}\"> my_script_file

bash shell heredoc
1个回答
0
投票

您所采用的方法非常容易出错,以至于具体如何失败取决于细节,我认为不值得深入研究。

有几种更好的方法可以做到这一点。


使用函数

这具有明显且显着的优势,静态检查工具可以在检查父脚本时验证语法,而不是需要使用它们来打开生成的子脚本。

my_script() {
  while getopts ":lr:e:" option; do
    case ${option} in
       l) cat file.txt; exit;;
       e) vi file.txt; exit;;
       r) rm file.txt; exit;;
       *) echo "invalid option" >&2; exit 1;;
    esac
  done
}
printf '%s\n' '#!/usr/bin/env bash' "$(declare -f my_script)" 'my_script "$@"' >file

使用引用的定界符

cat >file <<'EOF'
#!/usr/bin/env bash
while getopts ":lr:e:" option; do
  case ${option} in
     l) cat file.txt; exit;;
     e) vi file.txt; exit;;
     r) rm file.txt; exit;;
     *) echo "invalid option" >&2; exit 1;;
  esac
done
EOF
© www.soinside.com 2019 - 2024. All rights reserved.