Alexander Mills
Alexander Mills

Reputation: 100010

Adding bash functions to the $PATH or to bash shell automatically

Is there a way to add bash functions to the $PATH, or to the bash shell, without requiring an end-user to source them manually?

In other words, if we have a software library that exports only bash functions, we normally require the end-user to source the bash scripts with

. "$HOME/.the_scripts/"*.sh

and then using them. But is there a way to somehow get the bash functions into the shell without requiring the user to add a line of code to ~/.bashrc or ~/.bash_profile, etc?

What am I trying to do? I am trying to obviate the need for users to add a call to source a bash script for a library they just installed.

Upvotes: 1

Views: 3195

Answers (2)

glenn jackman
glenn jackman

Reputation: 246807

If you read about the Bash Startup Files, you notice that /etc/profile is one of the files that is processed. If you read that file, you'll see that it sources all *.sh files in /etc/profile.d

If you can have your script libraries installed in /etc/profile.d, the functions will be available for all interactive login shell sessions.

Upvotes: 1

Alexander Mills
Alexander Mills

Reputation: 100010

One suggestion I got was to write a container script, to a folder, where that folder is already in the $PATH.

Say I have a script like so:

#!/usr/bin/env bash

my_func(){
   echo "this is my func, $1, $2, $3"
   export foo="my_func"
}

my_func a b c

I could write that script to a folder in $PATH and then execute the script, which will then call the bash function(s).

Not sure how great/universal a solution this is, but it would work for some use cases I suppose. This will not work if you want to export env variables to the current shell, etc, because the bash function(s) would be run in a subshell as far as I know from the command line / current script.

Upvotes: 1

Related Questions