3

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?

4
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
| improve this answer | |
  • Very helpful! However, I don't understand your second example (with the "here" file) at all. I don't think I need to understand it for the answer to my question...but would you mind clarifying it? – Wildcard Nov 16 '15 at 21:22
  • @Wildcard - the <<INFILE here document is a redirection. it is not evaluated at define time, but only at call time, exactly as evaluations for $@ and $v are delayed. – mikeserv Nov 16 '15 at 21:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.