首页 > 解决方案 > 在macos下连接bash中的变量时避免空格

问题描述

bash在 macos 下遇到了一个奇怪的问题。当我连接两个变量时,它会在它们之间增加一个我无法摆脱的额外空间。

~/testdrive/dir1 $ curd=$(pwd)
~/testdrive/dir1 $ echo $curd
/xx/xx/testdrive/dir1
~/testdrive/dir1 $ fcount=$(ls -l | wc -l)
~/testdrive/dir1 $ echo $fcount
5          # notice no space in front of the 5 
~/testdrive/dir1 $ echo $curd$fcount
/xx/xx/testdrive/dir1 5 # space between directory name and 5

我正在使用 GNU bash,版本 5.0.16(1)-release (x86_64-apple-darwin19.3.0)。我尝试了 newd="$curd$fcount" 和 newd=${curd}${fcount} ,结果相同。在某些目录中,它会在变量之间添加 5 个或更多空格。

然而,

~/testdrive/dir1 $ var1=abc
~/testdrive/dir1 $ var2=def
~/testdrive/dir1 $ echo $var1$var2
abcdef   # expected behavior

然后,再次,

~/testdrive/dir1 $ echo $var1$fcount
abc 5  # space between

我已经看到了许多如何从字符串中删除空格的技巧,但是我不明白为什么它首先存在。我假设它与fcount=$(ls -l | wc -l)但如何?有任何想法吗?

标签: bashmacos

解决方案


Bash 变量是无类型的。尝试这个:

fcount=$(ls | wc -l)

echo $fcount          # check it
469                   # it looks ok, but...

echo "$fcount"        # ... when quoted properly
     469              # it has leading spaces! UGH!

再试一次,但这次告诉bash它是一个整数:

declare -i fcount     # Tell bash it's an integer
fcount=$(ls | wc -l)  # set it
echo "$fcount"        # check value with correct quoting
469                   # and it's correct

或者,如果您不喜欢该方法,您可以告诉bash将所有空格替换为空/空。

string="   abc  |"

echo "$string"           # display string as is
   abc  |

echo "${string// /}"     # delete all spaces in string
abc|

推荐阅读