Pal*_*han 3 bash shell newline
我正在浏览bash中的一个脚本,根据条件我想要附加到变量不同的东西,然后在最后显示它,如下所示:
VAR="The "
if [[ whatever ]]; then
VAR="$VAR cat wears a mask"
elif [[ whatevs ]]; then
VAR="$VAR rat has a flask"
fi
Run Code Online (Sandbox Code Playgroud)
但是如果我想在偶尔添加换行符时尝试使用这种形式来建立VAR,我会遇到困难.VAR="$VAR\nin a box"例如,我该怎么办?我已经看到过$'\n'之前的用法,但是$VAR因为附加而没有尝试使用.
使用ANSI-C引用:
var="$var"$'\n'"in a box"
Run Code Online (Sandbox Code Playgroud)
你可以把$'\n'变量放在:
newline=$'\n'
var="$var${newline}in a box"
Run Code Online (Sandbox Code Playgroud)
顺便说一下,在这种情况下,最好使用连接运算符:
var+="${newline}in a box"
Run Code Online (Sandbox Code Playgroud)
如果您不喜欢ANSI-C引用,可以使用printf其-v选项:
printf -v var '%s\n%s' "$var" "in a box"
Run Code Online (Sandbox Code Playgroud)
然后,要打印变量的内容var,不要忘记引号!
echo "$var"
Run Code Online (Sandbox Code Playgroud)
或者,更好的是,
printf '%s\n' "$var"
Run Code Online (Sandbox Code Playgroud)
备注.不要在Bash中使用大写变量名.这很可怕,有一天它会与现有的变量冲突!
您还可以创建一个函数,使用间接扩展将换行符和字符串附加到变量(请参阅本手册的Shell参数扩展部分),如下所示:
append_with_newline() { printf -v "$1" '%s\n%s' "${!1}" "$2"; }
Run Code Online (Sandbox Code Playgroud)
然后:
$ 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"
Run Code Online (Sandbox Code Playgroud)
只是为了好玩,这里是一个带有n + 1个参数(n≥1)的append_with_newline函数的通用版本,它将使用换行符连接它们(除了第一个是将要展开的变量的名称)分隔符,并将答案放在变量中,变量的名称在第一个参数中给出:
concatenate_with_newlines() { local IFS=$'\n'; printf -v "$1" '%s\n%s' "${!1}" "${*:2}"; }
Run Code Online (Sandbox Code Playgroud)
看看它的工作原理:
$ var="hello"
$ concatenate_with_newlines var "a gorilla" "a banana" "and foobar"
$ printf '%s\n' "$var"
hello
a gorilla
a banana
and foobar
$ # :)
Run Code Online (Sandbox Code Playgroud)
这是一个有趣的伎俩IFS和"$*".
| 归档时间: |
|
| 查看次数: |
4291 次 |
| 最近记录: |