0

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

András Gyömrey
  • 1,770
  • 1
  • 15
  • 36

2 Answers2

2

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

oliv
  • 12,690
  • 25
  • 45
  • Thank you for your answer, I just updated the question to address the reason that simplification doesn't work. – András Gyömrey Oct 30 '17 at 13:25
  • Why are the args not still considered a single string argument when passed in a single set of double quotes from `func` to `nested_func`? At first glance I'd've expected it all to be stacked into nested_`func`'s $1, though it works beautifully. – Paul Hodges Oct 30 '17 at 13:25
  • @AndrasGyomrey: This is the right answer. In `nested_func()` just loop over all the postional arguments as needed. it can be extended for any number of arguments – Inian Oct 30 '17 at 13:26
  • The problem is the first parameter is for `func`, whereas the second parameter is a **list** of parameters for `nested_func`. One possibility to use this solution would be to unshift the fixed amount of parameters `func` expects out of `"$@"` to leave the rest for `nested_func` – András Gyömrey Oct 30 '17 at 13:29
0

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

Joaquin
  • 2,013
  • 3
  • 14
  • 26