此代码在 Linux 上运行良好,但在 Mac OS 上运行不佳:
#!/usr/bin/env bash
foo=$(cat <<EOF
"\[^"\]+"
EOF
)
printf "%s" "$foo"
在 Mac 上失败
./test.sh: line 6: unexpected EOF while looking for matching `"'
./test.sh: line 7: syntax error: unexpected end of file
如果我这样做cat <<EOF
而不是foo=$(cat <<EOF
,它工作得很好。有没有一种可移植的方法可以将 heredocs (或多行字符串) 放入变量中,而无需使用文件作为中间体?
编辑:我想使用 heredoc,因为我有一个带有 和 的多行字符串"
。'
我的实际示例如下:
EXPECTED_ERROR=$(cat <<EOF
Set
: Type
File "/tmp/tmp[A-Za-z0-9_/]\+\.v", line 1\(0\|1\), characters 0-15:
Error: The command has not failed\s\?!
.\?Does this output display the correct error? \[(y)es/(n)o\]\s
I think the error is 'Error: The command has not failed\s\?!
.\?'\.
The corresponding regular expression is 'File "\[^"\]+", line (\[0-9\]+), characters \[0-9-\]+:\\\\n(Error:\\\\s+The\\\\s+command\\\\s+has\\\\s+not\\\\s+failed.*
EOF
)