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?

2
  • 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?" 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. Commented Sep 20, 2021 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. Commented Sep 21, 2021 at 5:19

2 Answers 2

2

Change

func1 $FLAGS

to

func1 "$FLAGS"

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

Sign up to request clarification or add additional context in comments.

Comments

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.