gpt4 book ai didi

bash - 用空格缩进 heredocs

转载 作者:行者123 更新时间:2023-11-29 08:42:25 26 4
gpt4 key购买 nike

对于我从事的个人发展和项目,我们使用四个空格而不是制表符。但是,我需要使用 heredoc,而且我不能在不破坏缩进流的情况下这样做。

我能想到的唯一可行的方法是:

usage() {
cat << ' EOF' | sed -e 's/^ //';
Hello, this is a cool program.
This should get unindented.
This code should stay indented:
something() {
echo It works, yo!;
}
That's all.
EOF
}

有更好的方法吗?

让我知道这是否属于 Unix/Linux Stack Exchange相反。

最佳答案

(如果您使用的是 bash 4,请滚动到末尾,我认为这是纯 shell 和可读性的最佳组合。)

对于 heredocs,使用制表符不是偏好或风格的问题;这就是语言的定义方式。

usage () {
⟶# Lines between EOF are each indented with the same number of tabs
⟶# Spaces can follow the tabs for in-document indentation
⟶cat <<-EOF
⟶⟶Hello, this is a cool program.
⟶⟶This should get unindented.
⟶⟶This code should stay indented:
⟶⟶ something() {
⟶⟶ echo It works, yo!;
⟶⟶ }
⟶⟶That's all.
⟶EOF
}

另一种选择是完全避免使用此处文档,代价是必须使用更多引号和续行:

usage () {
printf '%s\n' \
"Hello, this is a cool program." \
"This should get unindented." \
"This code should stay indented:" \
" something() {" \
" echo It works, yo!" \
" }" \
"That's all."
}

如果您愿意放弃 POSIX 兼容性,您可以使用数组来避免显式的行继续:

usage () {
message=(
"Hello, this is a cool program."
"This should get unindented."
"This code should stay indented:"
" something() {"
" echo It works, yo!"
" }"
"That's all."
)
printf '%s\n' "${message[@]}"
}

以下再次使用此处文档,但这次使用 bash 4 readarray命令来填充数组。参数扩展负责从每个谎言的开头删除固定数量的空格。

usage () {
# No tabs necessary!
readarray message <<' EOF'
Hello, this is a cool program.
This should get unindented.
This code should stay indented:
something() {
echo It works, yo!;
}
That's all.
EOF
# Each line is indented an extra 8 spaces, so strip them
printf '%s' "${message[@]# }"
}

最后一个变体:您可以使用扩展模式来简化参数扩展。不必计算缩进使用了多少空格,只需使用选定的非空格字符结束缩进,然后匹配固定前缀即可。我用 : . (以下空格冒号是为了便于阅读;可以通过对前缀模式进行微小更改来删除它。)

(另外,顺便说一句,使用以空格开头的 here-doc 定界符的非常好的技巧的一个缺点是它会阻止您在 here-doc 内执行扩展。如果你想这样做,你必须要么让定界符不缩进,要么对你的无制表符规则做一个小异常(exception),并使用 <<-EOF 和制表符缩进的结束定界符。)

usage () {
# No tabs necessary!
closing="That's all"
readarray message <<EOF
: Hello, this is a cool program.
: This should get unindented.
: This code should stay indented:
: something() {
: echo It works, yo!;
: }
: $closing
EOF
shopt -s extglob
printf '%s' "${message[@]#+( ): }"
shopt -u extglob
}

关于bash - 用空格缩进 heredocs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33815600/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com