gpt4 book ai didi

bash - 在macos下连接bash中的变量时避免空格

转载 作者:行者123 更新时间:2023-12-04 10:33:26 28 4
gpt4 key购买 nike

我遇到了一个奇怪的问题 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|

关于bash - 在macos下连接bash中的变量时避免空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60304745/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com