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.

Alexander Mills
  • 9,330
  • 19
  • 95
  • 180
  • 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 01 '18 at 11:47

3 Answers3

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"; }
glenn jackman
  • 84,176
  • 15
  • 116
  • 168
2

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

RudiC
  • 8,889
  • 2
  • 10
  • 22
0

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.

Alexander Mills
  • 9,330
  • 19
  • 95
  • 180