Reputation: 23
I am having a strange issue with bash
under macos. When I concatenate two variables, it adds an extra space between them which I cannot get rid of.
~/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
I am using GNU bash, Version 5.0.16(1)-release (x86_64-apple-darwin19.3.0). I tried newd="$curd$fcount" and newd=${curd}${fcount} with the same result. In some directories it adds 5 or more spaces between the variables.
However,
~/testdrive/dir1 $ var1=abc
~/testdrive/dir1 $ var2=def
~/testdrive/dir1 $ echo $var1$var2
abcdef # expected behavior
Then, again,
~/testdrive/dir1 $ echo $var1$fcount
abc 5 # space between
I've seen many tips how to remove whitespace from strings, however I do not understand why it is there in the first place. I am assuming it has to do with fcount=$(ls -l | wc -l)
but how? Any ideas?
Upvotes: 2
Views: 67
Reputation: 207708
Bash variables are untyped. Try this:
fcount=$(ls | wc -l)
echo $fcount # check it
469 # it looks ok, but...
echo "$fcount" # ... when quoted properly
469 # it has leading spaces! UGH!
Try again, but this time tell bash
it's an integer:
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
Or, if you don't like that method, you can tell bash
to replace all spaces with nothing/emptiness.
string=" abc |"
echo "$string" # display string as is
abc |
echo "${string// /}" # delete all spaces in string
abc|
Upvotes: 2
Reputation: 5056
It works for me :
$ name='john'
$ age='5'
$ echo "${name}${age}"
john5
I am using :
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin18)
Copyright (C) 2007 Free Software Foundation, Inc.
Please try to replicate this in your version. Otherwise this might work too :
$ newvalue=$( printf "%s%s\n" $name $age )
$ echo "$newvalue"
john5
Upvotes: 0