Bash – append text to a variable

Variable in string approach

Use curly braces {} around variable (${VARNAME}) in case text begins with alphanumeric character.

#!/bin/bash
A="HelloA"
B="$A Some other string"
echo $B
B="${A}Some other string"
echo $B
HelloA Some other string
HelloASome other string
Env: GNU bash, version 4.3.11

Concatenate variable with string

#!/bin/bash
A="HelloA"
B=$A"Some other string"
echo $B
HelloASome other string
Env: GNU bash, version 4.3.11

Use =+ operator

Everything by default treated as string by += operator.

#!/bin/bash
A="HelloA"
A+=" Some other string"
echo $A
A=1
A+=2
echo $A
HelloA Some other string
12
Env: GNU bash, version 4.3.11

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments