How does the source bash snippet conditionally expose a search wrapper function?

Is it possible to source the Bash fragment, but only actually provide the function from the inside if a certain condition is met?

So I ask that I can unconditionally transfer all files from the directory, but the source files contain logic to provide functions to the source shell or not.

Example:

  • .bashrc source of the entire subfolder .bashrc.d
  • .bashrc.d/xyzprovides a function adduser2groupthat works on older systems where it usermoddoes not process-a -G
  • .bashrc.d/xyz should provide this function only to the source shell if it works on such an old system.

My current method is to conditionally create aliaswith a name adduserafter the Debian ( alias adduser=adduser2group) program . Therefore, I use only semantics adduser <user> <group>, but still it is useful.

Is there a solution that does not require this workaround? In the end, this method means the likelihood of name collisions that I would rather avoid.

+5
source share
3 answers

You can define the necessary functions and, whenever a certain condition is met, you simply disable the function:

$ function alpha() { echo $1; }
$ alpha 10
10

Assessing your condition - and considering that this is true:

$ if [[ your condition ]]; then unset alpha; fi
$ alpha 10
alpha: command not found
+2
source

You can use standard shell logic to control whether functions are defined.

lib.sh:

if true; then
    foo() {
        echo foo
    }
else
    bar() {
        echo bar
    }
fi

test:

#!/bin/bash

. ./lib.sh
foo
bar

When it starts, it is determined only foo:

$ bash test
foo
test: line 5: bar: command not found

if true ...

+3

, , return . :

[[ condition ]] || return
+1
source

All Articles