小编Sam*_*nde的帖子

使用单空格或双空格时的 Bash 变量扩展行为

我在 bash 备份脚本中遇到了由我不理解的以下行为引起的问题。

首先,我们创建一个参数,其中包含一个包含 2 个连续空格的字符串(就在 '<' 之前):

me@mysystem:~$ TEST="a string with 2 spaces right  <--HERE!"
me@mysystem:~$ echo $TEST
a string with 2 spaces right <--HERE!
Run Code Online (Sandbox Code Playgroud)

我可以 grep 一个空间:

me@mysystem:~$ echo ${TEST} | grep " "
a string with 2 spaces right <--HERE!
Run Code Online (Sandbox Code Playgroud)

我可以 grep 一个空格后跟另一个字母:

me@mysystem:~$ echo ${TEST} | grep " s"
a string with 2 spaces right <--HERE!
Run Code Online (Sandbox Code Playgroud)

我可以在 2 个空格之后 grep 部分:

me@mysystem:~$ echo ${TEST} | grep "HERE"
a string with 2 spaces right <--HERE!
Run Code Online (Sandbox Code Playgroud)

我可以做一个变量扩展,用下划线替换两个空格:

me@mysystem:~$ …
Run Code Online (Sandbox Code Playgroud)

bash scripts

4
推荐指数
1
解决办法
8369
查看次数

标签 统计

bash ×1

scripts ×1