How to concatenate string variables in Bash

后端 未结 30 1548
攒了一身酷
攒了一身酷 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:02

    I prefer to use curly brackets ${} for expanding variable in string:

    foo="Hello"
    foo="${foo} World"
    echo $foo
    > Hello World
    

    Curly brackets will fit to Continuous string usage:

    foo="Hello"
    foo="${foo}World"
    echo $foo
    > HelloWorld
    

    Otherwise using foo = "$fooWorld" will not work.

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

    I do it this way when convenient: Use an inline command!

    echo "The current time is `date`"
    echo "Current User: `echo $USER`"
    
    0 讨论(0)
  • 2020-11-22 04:04

    Bash also supports a += operator as shown in this code:

    A="X Y"
    A+=" Z"
    echo "$A"
    

    output

    X Y Z

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

    If you want to append something like an underscore, use escape (\)

    FILEPATH=/opt/myfile
    

    This does not work:

    echo $FILEPATH_$DATEX
    

    This works fine:

    echo $FILEPATH\\_$DATEX
    
    0 讨论(0)
  • 2020-11-22 04:07

    There's one particular case where you should take care:

    user=daniel
    cat > output.file << EOF
    "$user"san
    EOF
    

    Will output "daniel"san, and not danielsan, as you might have wanted. In this case you should do instead:

    user=daniel
    cat > output.file << EOF
    ${user}san
    EOF
    
    0 讨论(0)
  • 2020-11-22 04:07
    var1='hello'
    var2='world'
    var3=$var1" "$var2 
    echo $var3
    
    0 讨论(0)
提交回复
热议问题