Bash Append Text To a Variable

by on August 14, 2006 · 8 comments· LAST UPDATED February 4, 2013

in , ,

How do I append additional text a variable? For e.g., I've a vech set as follows:
vech="London"
I'd like to add (append) "Bus" word to $vevh under UNIX scripting using bash?

You can simply use the following syntax:

vech="London"
vech="$vech Bus"
echo $vech

If you don't want to update $vech, but just want to print it on screen, enter:

echo "$vech Bus"

You can also append another variable:

x="Mango"
y="Pickle"
x="$x $y"
echo "$x"

Finally:

 
x="Master"
# print 'Master' without a whitespace i.e. print Mastercard as a one word #
echo "${x}card"
 


If you would like to be kept up to date with our posts, you can follow us on Twitter, Facebook, Google+, or even by subscribing to our RSS Feed.


{ 8 comments… read them below or add one }

1 [skqr] February 1, 2010 at 8:34 pm

What you are doing there is redefining it.

It’s completely useless.

When appending stuff to a variable, the most likely scenario is doing it while on a loop or an “if” block.

Redefining a variable in that context will just make it invisible once you get out of the loop or the “if” block.

Reply

2 gimmer March 12, 2011 at 2:32 pm

Isn’t that response just as useless? You don’t provide an alternative.

Reply

3 Kristof Wevers April 15, 2011 at 3:42 pm

Reply on old post but useful for someone who stumbles upon this

vech=”London”
vech=$vech” Bus”
echo $vech

Reply

4 Kristof Wevers April 15, 2011 at 3:44 pm

Scratch that, should be

vech=”London”
echo $vech” Bus”

Reply

5 Boris September 14, 2011 at 11:41 am

Jee thanks for Your site. Google frequently drives me here.

Reply

6 randy February 4, 2013 at 1:46 am

Sample given above does not work if there is no space:

vech=”Apple”
vech=”$vechseed”
echo $vech

^ ^ ^ Does not give you “Appleseed”

Reply

7 nixCraft February 4, 2013 at 8:12 am
vech="Apple"
vech="${vech}seed"
echo "$vech"

Reply

8 randy February 4, 2013 at 10:40 am

Thanks nixCraft! … Your example works for me and I think completes all possible scenarios that might apply to the original question. I also observed now in my experiment, the following produce expected results:

vech=”${vech}seed” # your original solution
vech=”${vech}+:;{[seed” # embed special syntax character works fine
vech=”${vech} seed” # embedding spaces also works fine
vech=${vech}”seed” # shifting the first double quote to the right
vech=${vech}” seed” # shifting the quote and embedding spaces
vech=${vech}”+:;{[seed” # shifted double quote w/special character

Reply

Leave a Comment

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul> <kbd> <blockquote> <pre> <a href="" title="">

Tagged as: , , , , , , ,

Previous Faq:

Next Faq: