Sample Header Ad - 728x90

Localising variables in /bin/sh functions

3 votes
2 answers
108 views
POSIX defines [shell functions](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_05) as:
fname ( ) compound-command [io-redirect ...]
The [compound-command](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_04) is further defined as either:
( compound-list )
{ compound-list ; }
In particular POSIX notes for the first form that "_variable assignments and built-in commands that affect the environment shall not remain in effect after the list finishes._" I've noticed that the idiomatic structure with bash code seems to be to use a braced compound list with the local keyword: f1() { local arg1=$1 arg2=$2 p q # arg1, arg2, p, q are all local vars shift 2 … } In general, assuming the function doesn't modify global variables, we can simplify this to use the bracketed form that implicitly localises all its variables: f2() ( arg1=$1 arg2=$2 # all variables are implicitly local shift 2 … ) Aside from using local as an explicit declaration of local variables, is there any general reason to prefer the braced f1() { …; } construct, which seems to be more commonly used than f2() ( … )?
Asked by Chris Davies (126603 rep)
Jul 30, 2025, 04:18 PM
Last activity: Aug 1, 2025, 01:09 PM