1

I try to expose from a script only specific functions.
For example, let's say I have the script hello_world.sh and it has 2 functions, hello and world:

## hello_world.sh - name of the file, not the beginning of file
hello() { echo "Hello"; }
world() { echo "World"; }

I want the script use.sh to export only the function I ask for, example hello. For this I would call the function use from use.sh with a parameter to tell it which function I desire to have exported:
unset use hello world; . use.sh && use hello && hello && echo "Should succeed"
world || echo "Should fail and reach here because there is no such function"

I would like to avoid storing the functions in temporary files in order to isolate better different (ba)sh environments. Storing in a temporary file could look something like this:

## use.sh - name of the file, not the beginning of file
#! /bin/sh

use() {
  local env_file="$(/bin/mktemp)"
  (. ./hello_world.sh; declare -pfx "$@") > "${env_file}"
  . "${env_file}"
  /bin/rm -f "${env_file}"
}

How could I instead not create files(it feels like some kind of work-around) and expose directly the functions?

1 Answer 1

1

You can use process substitution, so that use would look like:

use() {  
  . <(. ./hello_world.sh; declare -f "$@")
}

Side note:

  • declare is not POSIX, /bin/sh may not support it, so use.sh shouldn't have /bin/sh in the shebang. (Not that it matters much, since use.sh is sourced instead of executed.)
1
  • It works, thanks! I tried doing this but I was leaving a space between "<" and "(", didn't know that it makes a difference. May 26, 2016 at 10:05

You must log in to answer this question.

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