简体   繁体   中英

A bash function to act as an alias to directory of executables?

I found it hard to come up with a suitable title. Here's what I'd like to have:

$ some_prefix deploy

Should run an executable called deploy in /some/directory/somewhere where I can substitute "deploy" for any other executable in that directory. I could add /some/directory/somewhere to my PATH, but some of the scripts have generic names so I'd like to call them with a prefix.

I think you just want a function that hard-codes a path:

run_it () {
    "/some/directory/somewhere/$1" "${@:2}"
}

Then call

run_it deploy foo bar baz

to run

/some/directory/somewhere/deploy foo bar baz

Make a function or alias called setmy , that will set a lot of alias functions based on the list of executables in /some/directory/somewhere .
Your setmy will perform alias mydeploy=/some/directory/somewhere/deploy for all executables.
Next call your function with prefix my , only skip the space:

mydeploy

You can temporarily redefine the value of PATH by prepending its definition to the command:

PATH=/some/directory/somewhere:/usr/local/bin:/usr/bin:/bin deploy

This can also be packed into an alias:

alias some_prefix='PATH=/some/directory/somewhere:$PATH'

So that you only need to run:

some_prefix deploy

The shell ( bash , zsh or even dash ), will first expand the alias

PATH=/some/directory/somewhere:$PATH deploy

and then the PATH parameter

PATH=/some/directory/somewhere:/usr/local/bin:/usr/bin:/bin deploy

before using the redefined PATH to search for the deploy command and also passing it onto the environment of the deploy process.


Note: The definition is scoped only to the following command, not to the whole command line. So, if you run

some_prefix deploy ; deploy

only the first deploy will be searched in the modified PATH , while the second uses the original value of PATH . The same holds true for commands that are chained with | , && or || . If that is an issue, you might want to have a look at this question . Of course it is always possible to just use the alias multiple times as needed:

some_prefix deploy; some_prefix deploy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM