Tuesday, April 14, 2020

BASH Concatenate Exampls

The simplest way to concatenate two or more string variables is to write them one after another:
VAR1="Hello,"
VAR2=" World"
VAR3="$VAR1$VAR2"
echo "$VAR3"
The last line will echo the concatenated string:
Hello, World
You can also concatenate one or more variable with literal strings:
VAR1="Hello, "
VAR2="${VAR1}World"
echo "$VAR2"

  Hello, World
Copy1
In the example above variable VAR1 is enclosed in curly braces to protect the variable name from surrounding characters. When the variable is followed by another valid variable-name character you must enclose it in curly braces ${VAR1}.
Always try to use double quotes around the variable name. If you want to suppress variable interpolation and special treatment of the backslash character instead of double use single quotes.
Bash does not segregate variables by “type”, variables are treated as integer or string depending on contexts. You can also concatenate variables that contain only digits.
VAR1="Hello, "
VAR2=99
VAR3=" Worlds"
VAR4="$VAR1$VAR2$VAR3"
echo "$VAR4"
Copy1
Hello, 99 Worlds
Copy1
Concatenating Strings with the += Operator
Another way of concatenating strings in bash is by appending variables or literal strings to a variable using the += operator:
VAR1="Hello,"
VAR1+="World"
echo "$VAR1"
Copy1
Hello,World
Copy1
Copy
The following example is using the += operator to concatenate strings in bash for loop:
VAR=""
for combination in 'abc' 'def' 'ghi' 'jkl'; do
  VAR+="${combination} "
done
echo "$VAR"
Copy1
abc def ghi jkl
Copy1
Copy


No comments:

Post a Comment