Pedro Cattori
Pedro Cattori

Reputation: 2805

Modularizing and distributing bash script via Homebrew

Context

I have some functions defined in my ~/.bashrc which I'd like to turn into a Homebrew package. Currently, these functions act as custom commands on my command line:

# .bashrc
function foo() {
    # do something interesting
}

# at terminal
$ foo
# => does the interesting thing

Approach

I've created a homebrew formula using brew create. My current approach is as follows:

  1. Move the function definitions into a separate file, script, within a directory, brew-script
  2. Make brew-script downloadable as a tarball, brew-script.tar.gz
  3. Have my brew formula append text to the end of ~/.bash_profile to include script when terminal session starts

Concerns

  1. Is modifying .bash_profile in a brew formula bad practice? (eg. when uninstalling with brew uninstall script, brew should somehow remove the text that was appended to .bash_profile... Parsing .bash_profile doesn't seem very fun.)

  2. Is there a convention already established for including functions in bash scripts so that they are available from the command line?

  3. Is it common to simply ask the user to add some text to their .bash_profile or .bashrc?

Desired result

Should be able to install cleanly with brew and then run foo as a command:

$ brew install script
$ foo
# => does the interesting thing

(Assume the brew formula is already installed locally. I'll worry about auditing and pushing the formula to homebrew later)

Upvotes: 7

Views: 2524

Answers (2)

Artemis
Artemis

Reputation: 1

Without using homebrew:

to put your bash scripts in some file such as bashrc or any other name works, then put the following line:

source "path/to/brew-script/script"

somewhere in your bash profile.

Then you just have to make sure you refresh or reload your bash profile by running . ~/.bash_profile or source ~/.bash_profile.

How homebrew installs work:

When you installed homebrew it added a line to your bash_profile that modifies your $PATH variable to include the path to the homebrew install repo, so that whenever brew installs something it becomes findable through your PATH. If you use brew create you must have your script uploaded somewhere on the internet, because the argument brew install takes is a URL. I.e if I create my script at my_bash_function.tar.gz then I would do

brew create http://web.mit.edu/dianah13/www/my_bash_function.tar.gz

It also templates a pull request to include your package in homebrew's main repo.

Upvotes: 0

paul_h
paul_h

Reputation: 2051

Refer https://github.com/Homebrew/homebrew/issues/50232 and https://github.com/Homebrew/homebrew/issues/50231.

I have a script that safely‡ modifies ~/.bash_profile as part of a homebrew install process. https://github.com/paul-hammant/homebrew-tap/blob/master/switchjdk.rb

‡ allegedly

Upvotes: 1

Related Questions