András Gyömrey
András Gyömrey

Reputation: 1829

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

Upvotes: 0

Views: 517

Answers (2)

Joaquin
Joaquin

Reputation: 2091

I have the expected output with this:

#!/bin/bash
nested_func() {
    echo $1
    echo $2
}

func() {
    echo $1
    nested_func ${2%% *} "${2#* }"
}

func 1 "2 3.1 3.2"

Using Parameter expansion

Upvotes: 0

oliv
oliv

Reputation: 13249

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...

Upvotes: 2

Related Questions