How to concatenate string variables in Bash

后端 未结 30 1502
攒了一身酷
攒了一身酷 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 04:07

    I don't know about PHP yet, but this works in Linux Bash. If you don't want to affect it to a variable, you could try this:

    read pp;  *# Assumes I will affect Hello to pp*
    pp=$( printf $pp ;printf ' World'; printf '!');
    echo $pp;
    
    >Hello World!
    

    You could place another variable instead of 'Hello' or '!'. You could concatenate more strings as well.

    0 讨论(0)
  • 2020-11-22 04:11

    I kind of like making a quick function.

    #! /bin/sh -f
    function combo() {
        echo $@
    }
    
    echo $(combo 'foo''bar')
    

    Yet another way to skin a cat. This time with functions :D

    0 讨论(0)
  • 2020-11-22 04:13

    If what you are trying to do is to split a string into several lines, you can use a backslash:

    $ a="hello\
    > world"
    $ echo $a
    helloworld
    

    With one space in between:

    $ a="hello \
    > world"
    $ echo $a
    hello world
    

    This one also adds only one space in between:

    $ a="hello \
    >      world"
    $ echo $a
    hello world
    
    0 讨论(0)
  • 2020-11-22 04:14
    foo="Hello "
    foo="$foo World"
    

         

    0 讨论(0)
  • 2020-11-22 04:15

    The way I'd solve the problem is just

    $a$b
    

    For example,

    a="Hello"
    b=" World"
    c=$a$b
    echo "$c"
    

    which produces

    Hello World
    

    If you try to concatenate a string with another string, for example,

    a="Hello"
    c="$a World"
    

    then echo "$c" will produce

    Hello World
    

    with an extra space.

    $aWorld
    

    doesn't work, as you may imagine, but

    ${a}World
    

    produces

    HelloWorld
    
    0 讨论(0)
  • 2020-11-22 04:16

    Here is the one through AWK:

    $ foo="Hello"
    $ foo=$(awk -v var=$foo 'BEGIN{print var" World"}')
    $ echo $foo
    Hello World
    
    0 讨论(0)
提交回复
热议问题