Home > Blockchain >  Bash function argument from variable
Bash function argument from variable

Time:09-21

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?

CodePudding user response:

Change

func1 $FLAGS

to

func1 "$FLAGS"

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

CodePudding user response:

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
}
  •  Tags:  
  • bash
  • Related