How to concatenate string variables in Bash

后端 未结 30 1520
攒了一身酷
攒了一身酷 2020-11-22 03:40

In PHP, strings are concatenated together as follows:

$foo = \"Hello\";
$foo .= \" World\";

Here, $foo becomes \"Hello World\"

30条回答
  •  广开言路
    2020-11-22 03:57

    Here is a concise summary of what most answers are talking about.

    Let's say we have two variables and $1 is set to 'one':

    set one two
    a=hello
    b=world
    

    The table below explains the different contexts where we can combine the values of a and b to create a new variable, c.

    Context                               | Expression            | Result (value of c)
    --------------------------------------+-----------------------+---------------------
    Two variables                         | c=$a$b                | helloworld
    A variable and a literal              | c=${a}_world          | hello_world
    A variable and a literal              | c=$1world             | oneworld
    A variable and a literal              | c=$a/world            | hello/world
    A variable, a literal, with a space   | c=${a}" world"        | hello world
    A more complex expression             | c="${a}_one|${b}_2"   | hello_one|world_2
    Using += operator (Bash 3.1 or later) | c=$a; c+=$b           | helloworld
    Append literal with +=                | c=$a; c+=" world"     | hello world
    

    A few notes:

    • enclosing the RHS of an assignment in double quotes is generally a good practice, though it is quite optional in many cases
    • += is better from a performance standpoint if a big string is being constructed in small increments, especially in a loop
    • use {} around variable names to disambiguate their expansion (as in row 2 in the table above). As seen on rows 3 and 4, there is no need for {} unless a variable is being concatenated with a string that starts with a character that is a valid first character in shell variable name, that is alphabet or underscore.

    See also:

    • BashFAQ/013 - How can I concatenate two variables?
    • When do we need curly braces around shell variables?

提交回复
热议问题