Peter Dolan
Peter Dolan

Reputation: 1423

Is there a way to create aliases for only certain directories?

I'm looking for a way to assign an alias that only operates in a single folder, and is easily transferable via git.

I'm imagining some sort of .aliases file where I can create things like ALIAS test=pytest[....] that will be picked up by others when they pull from this repo.

Is such a thing possibly natively in OSX terminal, or would I need some sort of third party library/manual editing of everybody's .bashrc/.zshrc?

Thanks for the help, and if anything is unclear please let me know!

Upvotes: 8

Views: 4113

Answers (1)

Rory O'Kane
Rory O'Kane

Reputation: 30388

This is not possible natively. This is mainly for security reasons – you wouldn’t want to download a project, cd into its directory, and have it overwrite the ls command so that ls uploads all your files to a hacker.

There is a tool direnv for Mac and Linux that automatically loads environment variables from a .envrc file when you cd into a directory, which is close to what you want, but direnv doesn’t support defining aliases/functions. (And it requires direnv to be installed first.)

Here are some alternatives to aliases for making the same command run different things in different project directories. Which one you should choose depends on the conventions of your project and its ecosystem.

Shell scripts

A solution that works with many programming languages, but only on Unix, would be to include shell scripts:

test
#!/usr/bin/env bash
pytest ...

And tell people to run it with ./test.

You could also put all your scripts in a folder such as script and tell people to run script/test.

A Makefile

If you require Make to be installed, you could make your scripts cross-platform (which would require avoiding platform-specific commands in your scripts). You would define a Makefile containing your aliases:

Makefile
.PHONY: test
test:
    pytest ...

And tell people to run it with make test.

Language-specific scripts, e.g. package.json for JavaScript

Some languages have other conventions. For example, if you are using JavaScript with the NPM package manager, the convention is to put scripts in your package.json:

package.json
{
  "name": "my-js-project",
  ...,
  "scripts": {
    "test": "node tests.js"
  },
}

Then people would try the standard command npm test and it would call this script. If the script had a non-standard name, you could tell them to npm run test instead.

Upvotes: 11

Related Questions