18

Say one have a function/method foo. Can one use the local keyword to declare multiple variables in one line, or do they have to be separated by one declare statement for each variable?

foo()
{
    local x y z
}

or

foo()
{
    local x
    local y
    local z
}

And further:

foo()
{
    local -i x -a y  z
}

foo()
{
    local -i x=2 -a y=()  z
}

…

or the equivalent one by one line declaration.


Yes. Could test, but for one I can not find any Q/A on this, and second – there might be some hidden caveats 😏

2 Answers 2

19

Yes you can. A possible caveat is SC2155 in that you should declare and assign separately.

That being said it will work except for using multiple declare options between the parameters. Also note that the declare parameters will apply to all variables (in this case -i).

script0:

#!/bin/bash

declare a b c
a=foo
b=bar
c=baz

foo () {
    local a=1 b=2 c=3

    echo "From within func:"
    declare -p a
    declare -p b
    declare -p c
}

foo

echo "From outside func:"
declare -p a
declare -p b
declare -p c

Output:

$ ./script.sh
From within func:
declare -- a="1"
declare -- b="2"
declare -- c="3"
From outside func:
declare -- a="foo"
declare -- b="bar"
declare -- c="baz"

script1:

#!/usr/bin/env bash

declare -i a -a b c
a=foo
b=(bar)
c=baz

foo () {
    local -i a=1 -a b=(2) c=3

    echo "From within func:"
    declare -p a
    declare -p b
    declare -p c
}

foo

echo "From outside func:"
declare -p a
declare -p b
declare -p c

Output:

$ ./script.sh
./script.sh: line 3: declare: `-a': not a valid identifier
./script.sh: line 9: local: `-a': not a valid identifier
From within func:
declare -i a="1"
declare -ai b=([0]="2")
declare -i c="3"
From outside func:
declare -i a="0"
declare -ai b=([0]="0")
declare -i c="0"
5
  • So, if I read your link correctly, the caveat is merely if one assign a value by calling a function or command which might fail.
    – ibuprofen
    Commented Jun 27, 2019 at 21:34
  • @user3342816: Yes and even then it's really only an issue if you wanted to act on $? immediately after. Honestly I usually ignore SC2155 in my scripts because I almost never use $? but it's important to know for that reason.
    – jesse_b
    Commented Jun 27, 2019 at 21:38
  • @user3342816: I would also note my latest update about how the declare option will apply to all parameters being set
    – jesse_b
    Commented Jun 27, 2019 at 21:43
  • Yes. As with for example local a -i b c
    – ibuprofen
    Commented Jun 27, 2019 at 21:57
  • So; multiple of non-type or multiple of same type in one line. No mixing.
    – ibuprofen
    Commented Jun 27, 2019 at 22:01
8

To add to @jesse_b's excellent answer. I can confirm this also works (and takes into account the best practise of SC2155):

foo()
{
  local x y z
  x=1
  y=2
  z=3
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .