2

I have this:

foo(){
   install_ores_gitflow;
   command foo "$@"
}

export -f foo;

I am looking for something like this:

export foo(){
   install_ores_gitflow;
   command foo "$@"
}

but that syntax is not correct.

One technique I found is this: How to export all Bash functions in a file in one line?

so that means I could do this:

set -a;

foo(){
  install_ores_gitflow;
  command foo "$@"
}

set +a;

but I don't like that solution because the sourcing script could have set -a which means my script would override that which is very bad.

  • What specifically is wrong with export -f foo? – glenn jackman Aug 31 '18 at 21:31
  • bash is a dynamic language, I will refactor the name of the bash function, delete a bash function, etc, and forget to change the export lines. – Alexander Mills Aug 31 '18 at 21:32
  • Why do you like to do this? Exported functions are seen as a security risk and intentionally not part of POSIX. The clean way is to put the definitions into the interactive startup script or to let scripts source a file with the related definitions. – schily Sep 1 '18 at 11:47
3

This is a nasty hack, but at least it allows you to puts the export command above the function definition where it's easier to see it.

# a function to create a dummy function and export it
export_function() { eval "function $1 { :; }; export -f $1"; }

# then

export_function foo
foo() { echo "here is the *real* function"; }
  • I think I got it, see my answer, using the $SHELLOPTS env var – Alexander Mills Sep 1 '18 at 4:45
2

Why don't you check the -a option's status with e.g. echo $-, so no action needed if it is set?

  • that might work, can you give an example of that in full? A problem with that though is in many cases we don't want to export all bash functions. – Alexander Mills Aug 31 '18 at 21:33
  • how do I check if a is set with echo $-? – Alexander Mills Sep 1 '18 at 4:35
  • I think I got it, see my answer, using the $SHELLOPTS env var – Alexander Mills Sep 1 '18 at 4:45
1

Alright so I think this is a sane and reliable way to do it:

#!/usr/bin/env bash

if [[ ! "$SHELLOPTS" =~ "allexport" ]]; then
    set -a;
    all_export=nope;
fi


ores_git_merge_with_integration(){
   install_ores_gitflow;
   command "$FUNCNAME" "$@"
}

ores_git_tools(){
   install_ores_gitflow;
   command "$FUNCNAME" "$@"
}


if [ "$all_export" == "nope" ]; then
  set +a;
fi

in your bash script, potentially could group all your functions to be exported and surround them with the set -a / set + commands.

The purpose of checking the $SHELLOPTS env var is to see if set -a was not on, and if it wasn't, we need to turn it off when we are done.

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.