Differences between revisions 2 and 6 (spanning 4 versions)
Revision 2 as of 2007-11-07 07:17:10
Size: 1473
Editor: c-68-56-54-232
Comment: edited by Quiznos adding "explicit" and rephraseology
Revision 6 as of 2008-11-22 14:09:45
Size: 1555
Editor: localhost
Comment: converted to 1.6 markup
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
[[Anchor(faq13)]] <<Anchor(faq13)>>
Line 3: Line 3:
There is no(explicit) concatenation operator for strings (either literal or variable dereferences) in the shell, *BUT* one can concat the value of variables by naming eaching variable to be joined together. The variables whose content are to be concatenated are just written one after the other:

There is no (explicit) concatenation operator for strings (either literal or variable dereferences) in the shell, *BUT* one can concat the values of variables by sequentially naming eaching variable to be joined together. The variables whose values are to be concatenated are written one after the other:
Line 38: Line 40:
A variable's value (the string it holds) may be reassigned at will:

How can I concatenate two variables? How do I append a string to a variable?

There is no (explicit) concatenation operator for strings (either literal or variable dereferences) in the shell, *BUT* one can concat the values of variables by sequentially naming eaching variable to be joined together. The variables whose values are to be concatenated are written one after the other:

    var=$var1$var2

If the right-hand side contains whitespace characters, it needs to be quoted:

    var="$var1 - $var2"

If you're appending a string that doesn't "look like" part of a variable name, you just smoosh it all together:

    var=$var1/.-

Otherwise, braces or quotes may be used to disambiguate the right-hand side:

    var=${var1}xyzzy
    # Without braces, var1xyzzy would be interpreted as a variable name

    var="$var1"xyzzy
    # Alternative syntax

CommandSubstitution can be used as well. The following line creates a log file name logname containing the current date, resulting in names like e.g. log.2004-07-26:

    logname="log.$(date +%Y-%m-%d)"

There's no difference when the variable name is reused, either: A variable's value (the string it holds) may be reassigned at will:

    string="$string more data here"

Bash 3.1 has a new += operator that you may see from time to time:

    string+=" more data here"     # EXTREMELY non-portable!

It's generally best to use the portable syntax.

BashFAQ/013 (last edited 2018-07-06 10:01:46 by 83)