How to debug a bash function that returns a value, and how to add newlines to a variable?

前端 未结 3 1812
广开言路
广开言路 2020-12-20 17:04

I\'m in a bash crash course today.

This is a bash function that returns a value, via echo:

#!/bin/bash
get_hello_name() {
  echo \'Hello $1!\'
}
msg=         


        
3条回答
  •  鱼传尺愫
    2020-12-20 17:52

    The working code after following John1024's tips (note the newlines print in the "1" lines, but not the "4", because of the e option):

    #!/bin/bash
    a_function() {
        echo -e "Hello\nworld\n 1"
        echo "Hello"
        echo "world"
        echo "Hello\nworld 4"
    }
    
    echo -e "Hello\nworld\n 1"
    echo "Hello"
    echo "world"
    echo "Hello\nworld 4"
    
    x=$(a_function "x")
    echo "x-no-quotes>"
    echo $x                       #No new lines!
    echo ""
    echo "$x"                     #Yes new lines!
    echo "

    Output:

    Hello
    world
     1
    Hello
    world
    Hello\nworld 4
    x-no-quotes>
    Hello world 1 Hello world Hello\nworld 4
    
    Hello
    world
     1
    Hello
    world
    Hello\nworld 4
    

提交回复
热议问题