Bash – ny danger to using an unset variable in a bash function definition

bashfunctionlibrariesscripting

Doing some code refactoring, and I realized I don't know if this matters at all:

The function definition is going to be sourced from another file (a sort of library). The function uses certain variables within the function body. Those variables will be set by the time the function is actually called in the script, but it will be much cleaner if I can source the function library at the start of the script; however the variables aren't defined at this point.

Is there any disadvantage to doing this? As far as I know bash won't actually do anything with a function definition until it is called…right? In which case the unset variables used within the function won't matter, since those variables will contain the correct values later, before the function is actually called.

Or will it mess things up to include so-far-unset variables in a function definition?

Best Answer

fn(){ printf %s\\n "${v-not set}"; }
v=value; fn; unset v; fn

value
not set

A shell function is a literal string stored in the shell's memory. At define time it is parsed, but is not evaluated for expansions (other than shell aliases) or redirections. These are only evaluated at call time.

In fact, and somewhat related, in this way it is possible to get a function to define its own input with a new temporary file at each invocation.

fn(){ ls -l /dev/fd/0; cat; } <<INFILE
$@
INFILE
fn some args; fn other args

#in dash
lr-x------ 1 mikeserv mikeserv 64 Nov 16 12:50 /dev/fd/0 -> pipe:[4076148]
some args
lr-x------ 1 mikeserv mikeserv 64 Nov 16 12:50 /dev/fd/0 -> pipe:[4077081]
other args
#bash
lr-x------ 1 mikeserv mikeserv 64 Nov 16 12:51 /dev/fd/0 -> /tmp/sh-thd-1036060995 (deleted)
some args
lr-x------ 1 mikeserv mikeserv 64 Nov 16 12:51 /dev/fd/0 -> /tmp/sh-thd-531856742 (deleted)
other args