Search code examples
bashshellescapingparameter-passingparameter-expansion

Shell script variable expansion with escape


The following script:

#!/bin/bash

nested_func() {
    echo $1
    echo $2
}

func() {
    echo $1
    nested_func $2
}

func 1 "2 '3.1 3.2'"

Outputs:

1
2
'3.1

What I would like to get as output is:

1
2
3.1 3.2

How do I achieve this output with a single parameter on func instead of many?

EDIT made to address simplifications


Solution

  • You can try this:

    #!/bin/bash
    
    nested_func() {
        echo "$1"
        echo "$2"
    }
    
    func() {
        nested_func "$@"
    }
    
    func 1 '2.1 2.2'
    

    $@ represent all positional parameters given to the function


    As an alternative you can use this:

    #!/bin/bash
    
    nested_func() {
        echo "$1"
        echo "$2"
    }
    
    func() {
        echo "$1"
        shift
        nested_func "$@"
    }
    
    func 1 2 '3.1 3.2'
    

    The shift keyword allows to skip the first parameter.

    You can easily map this if you have 4 parameters...