P2000
P2000

Reputation: 1062

In bash, why does the "local" keyword pass function arguments?

In bash, it seems you can use the "local" keyword to refer to input arguments to a function. Is this documented behaviour? If so, where can I read about it?

$ f() { local g; for g; do echo $g; done; }
$ f foo bar
foo
bar

According to https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html

local [option] name[=value] … For each argument, a local variable named name is created, and assigned value.

But I see nothing about assigning the function's $1, $2 etc to the variable if no other value is provided.

I am more familiar with doing it this way:

for g in "$@"

Is either way better? More cross-compatible?

My bash on macOs 10.14:

GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin18) Copyright (C) 2007 Free Software Foundation, Inc.

Upvotes: 1

Views: 463

Answers (1)

Barmar
Barmar

Reputation: 780663

This has nothing to do with the local command. When you use the for command without the in clause, it defaults to looping over the positional arguments.

for g

is equivalent to

for g in "$@"

This is in the Bash Manual

If ‘in words’ is not present, the for command executes the commands once for each positional parameter that is set, as if in "$@" had been specified (see Special Parameters).

Upvotes: 2

Related Questions