bash - 在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)
但如何?有任何想法吗?
解决方案
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|
推荐阅读
- java - 对不同类型的对象具有相同验证规则的 Java 设计类
- javascript - 如何展平嵌套对象?
- ssis - 具有本地 C 驱动器与网络驱动器的 SSIS 包文件
- postgresql - 如何在rails 5中添加具有较低功能的三元组索引
- postgresql - 将 postgres 参数传递到 Kubernetes 部署中
- python - 寻找一种将行组合在一起的方法,以便在 Python/Pandas 中列匹配并且一列的数字大于或等于零
- heroku - DNS 目标和路由问题
- java - 如何将 Project Reactor 的调度程序与基于 Executor 的库一起使用?
- javascript - AJAX - 在一个 onchange 事件中调用两个函数
- python - Python 检查图像是灰度还是彩色的最快方法?