我正在bash中浏览一个脚本,在该脚本中,根据要附加到变量的条件不同,然后在最后显示它,如下所示:

VAR="The "

if [[ whatever ]]; then
    VAR="$VAR cat wears a mask"
elif [[ whatevs ]]; then
    VAR="$VAR rat has a flask"
fi

但是,如果我偶尔想在其中添加换行符,则尝试通过附加这种形式来构建VAR的方式而遇到麻烦。例如,我将如何VAR="$VAR\nin a box"?我以前曾经看过$'\n'的用法,但由于附加而在尝试使用$VAR时也没有见过。

最佳答案

使用ANSI-C quoting:

var="$var"$'\n'"in a box"

您可以将$'\n'放在一个变量中:
newline=$'\n'
var="$var${newline}in a box"

顺便说一句,在这种情况下,最好使用串联运算符:
var+="${newline}in a box"

如果您不喜欢ANSI-C引号,则可以将printf-v选项一起使用:
printf -v var '%s\n%s' "$var" "in a box"

然后,要打印变量var的内容,请不要忘记引号!
echo "$var"

或者,更好的是
printf '%s\n' "$var"

备注。 不要在Bash中使用大写的变量名。这太可怕了,有一天它将与一个已经存在的变量发生冲突!

您还可以使用间接扩展(在Shell Parameter Expansion section of the manual中进行查看)来制作一个函数,以将换行符和字符串附加到变量上,如下所示:
append_with_newline() { printf -v "$1" '%s\n%s' "${!1}" "$2"; }

然后:
$ var="The "
$ var+="cat wears a mask"
$ append_with_newline var "in a box"
$ printf '%s\n' "$var"
The cat wears a mask
in a box
$ # there's no cheating, look at the content of var:
$ declare -p var
declare -- var="The cat wears a mask
in a box"

只是为了好玩,这是append_with_newline函数的通用版本,它接受n + 1个参数(n≥1),并将所有参数连接起来(除了第一个是将被扩展的变量的名称),使用换行符作为分隔符,并将答案放在变量中,变量的名称在第一个参数中给出:
concatenate_with_newlines() { local IFS=$'\n'; printf -v "$1" '%s\n%s' "${!1}" "${*:2}"; }

看看效果如何:
$ var="hello"
$ concatenate_with_newlines var "a gorilla" "a banana" "and foobar"
$ printf '%s\n' "$var"
hello
a gorilla
a banana
and foobar
$ # :)

使用IFS"$*"是一个有趣的骗术。

关于bash - 用换行符在bash中构建字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19912681/

10-14 17:20
查看更多