我和macos下的bash有一个奇怪的问题。当我连接两个变量时,它会在它们之间增加一个额外的空间,这是我无法摆脱的。
~/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版本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)有关,但怎么做呢?有什么想法吗?
发布于 2020-02-19 16:27:03
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|发布于 2020-02-19 16:27:56
它适用于我:
$ name='john'
$ age='5'
$ echo "${name}${age}"
john5我正在使用:
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin18)
Copyright (C) 2007 Free Software Foundation, Inc.请试着在你的版本中复制这个。否则,这也可能奏效:
$ newvalue=$( printf "%s%s\n" $name $age )
$ echo "$newvalue"
john5https://stackoverflow.com/questions/60304745
复制相似问题