Bash Append Text To a Variable

last updated in Categories , , , , , , , ,

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

You can simply use the following syntax:

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="$x $y"
echo "$x"


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

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

10 comment

  1. 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.

    1. Actually it helped me, a lot xD well what i was looking for was on the last section but that’s ok. I wanted to automate g++ compilation, so i did:

      read -p "Enter cpp file name (without extension): " file
      echo "You selected ${file}.cpp"
      echo "The command to execute is:"
      echo "g++ -o $file ${file}.cpp -lSDL -lSDL_image -lSDL_ttf -lSDL_mixer"

      SO, not useless hehe

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

    vech=$vech” Bus”
    echo $vech

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

    echo $vech

    ^ ^ ^ Does not give you “Appleseed”

      1. 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

  4. I had a bit different need: to read the content of differente files and append it to a variable. By the way “+=” did the trick.

    #echo $JS_F
    for f in $JS_F
    echo $JS_C

    Still, have a question? Get help on our forum!