0

Consider the following code, where I defined two functions, func1 and func2:

func1 () {
    local FLAGS=${1}
    echo "func1 $FLAGS"
}

func2 () {
    local FLAGS=${1}
    echo "func2 $FLAGS"
    func1 $FLAGS
}

FLAGS="-p -i"
func1 $FLAGS
func2 $FLAGS

func1 "-p -i"
func2 "-p -i"

The aim is to pass an argument to them, in this case FLAGS="-p -i". I would expect that all the four calls above are equivalent. However, this is the output I'm getting:

func1 -p
func2 -p
func1 -p
func1 -p -i
func2 -p -i
func1 -p

This tells me that, whenever the argument is saved into a variable, it gets parsed and only the pre-white space part is passed to the function. My question is why is this happening and how to pass the entire $FLAG argument to the function, regardless of whether it contains spaces or not?

Botond
  • 2,640
  • 6
  • 28
  • 44
  • 1
    You should almost always put double-quotes around variable (and parameter) references, to avoid weird parsing problems like this. See ["When should I double-quote a parameter expansion?"](https://stackoverflow.com/questions/55023461/when-should-i-double-quote-a-parameter-expansion) [Shellcheck.net](https://www.shellcheck.net) is good at spotting common mistakes like this. BTW, I also recommend using lower- or mixed-case variable names, since there are a lot of all-caps names with special meanings and re-using one of those by mistake can also cause problems. – Gordon Davisson Sep 20 '21 at 20:39
  • @Botond: With `func1 "-p -i"` you pass (because of the quotes) a **single** argument `-p -i` to your function. With `func1 $FLAGS`, the shell first expands the variable `FLAGS` and performs word splitting on the expansion, which gives you `func1 -p -s`. With this you pass two arguments, `-p` and `-s`. – user1934428 Sep 21 '21 at 05:19

2 Answers2

2

Change

func1 $FLAGS

to

func1 "$FLAGS"

Without the quotes, '-p' is $1 and '-i' is $2

Dave Costa
  • 47,262
  • 8
  • 56
  • 72
2

My question is why is this happening

This is how it works.

and how to pass the entire $FLAG argument to the function

Like this:

func1 "$FLAGS"
func2 "$FLAGS"

Or change your functions like this:

func1 () {
    local FLAGS=${@}
    echo "func1 $FLAGS"
}

func2 () {
    local FLAGS=${@}
    echo "func2 $FLAGS"
    func1 $FLAGS
}
Ivan
  • 6,188
  • 1
  • 16
  • 23