6

Solaris / sh

I have a few functions defined in a file which gets loaded via

. ./some_file.sh 

When I start a subshell with

sh

All my function definitions are lost but when I do

env

I do see the source, is there an easy way to get them functional in my subshell?

6

Functions are naturally propagated to subshells:

greet () {
  echo "hello, $1"
}
( echo "this is a subshell"; greet bob )

But they are not and cannot be propagated to independent shell processes that you start by invoking the shell under its name.

Bash has an extension to pass functions through the environment, but there's no such thing in other shells. While you can emulate the feature, it requires running code in the nested shell anyway. You might as well source your function definitions in the nested shell.

5

You can propagate functions from bash to bash subshells:

function greet1 {
  echo "moin, $1"
}
typeset -fx greet1

greet2() {
  echo "servus, $1"
}
typeset -fx greet2

echo "greet1 bob; greet2 alice" | bash

Output:

moin, bob
servus, alice

Also, see https://docstore.mik.ua/orelly/unix3/upt/ch29_13.htm

  • We prefer our answers to have a bit more explanation.   And, if you’re going to link to another site, at least tell us what’s there. – Scott Aug 1 '17 at 16:00
  • Wow! This is first time when I saw answer by some "anon" user much better than top 0.01. – Alex Baranowski Apr 25 '18 at 13:59

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.