bash 在系统 (OSX) 中注册自定义 shell 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14193207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:11:15  来源:igfitidea点击:

Registering custom shell function in system (OSX)

bashfunctionshell.bash-profile

提问by lukaszkups

today I wanted to write a function which will deploy my blog page (developed in nanoc) to github pages automatically - here's the script:

今天我想编写一个函数来自动将我的博客页面(用 nanoc 开发)部署到 github 页面 - 这是脚本:

function cmit()
{
  nanoc compile;
  git add .;
  git commit -am ;
  git push origin source;
  cd output; git add .;
  git commit -am ;
  git push origin master;
  cd ..;
  echo 'new version deployed! now starting nanoc locally..';
  nanoc aco;
}

Example usage: cmit "my example commit!"

用法示例: cmit "my example commit!"

I don't really know how register my function in system (OSX) - in .bashrc, .bash_profileor maybe somewhere else? Please help!

我真的不知道如何注册我的系统(OSX)功能-在.bashrc.bash_profile也许别的地方?请帮忙!

回答by Chris Seymour

Just added it to the bottom of your ~/.bashrcfile then you will be able to use cmitlike a regular command, you will need to refresh your current shell to pick up the changes so run source ~/.bashrc. If you have the function saved in a file cmitjust do cat cmit >> ~/.bashrcto append the function to the end of your ~/.bashrc.

只需将它添加到~/.bashrc文件的底部,然后您就可以cmit像常规命令一样使用,您需要刷新当前的 shell 以获取更改,所以运行source ~/.bashrc. 如果您将函数保存在文件中,cmit只需cat cmit >> ~/.bashrc将该函数附加到~/.bashrc.

You could try out a test function first:

您可以先尝试一个测试功能:

# add to ~/.bashrc first
function test() {
    echo "Some test foo!"
}

$ source ~/.bashrc

$ test
Some test foo!

回答by cmc

You can put it in your .bashrc, it will work as long as you're logged as the owner of this .bashrcfile.

你可以把它放在你的.bashrc,只要你作为这个.bashrc文件的所有者登录它就会工作。

If you want it to be available for any user, put the content of your function in a script file, make it executable using chmodthen move it in /usr/bin(I'm assuming you have admin rights on that system)

如果您希望任何用户都可以使用它,请将您的函数内容放入脚本文件中,使其可执行,chmod然后将其移入/usr/bin(我假设您在该系统上具有管理员权限)

Note: typically you'd give it rwx rx rxrights, which corresponds to a chmod 755 my_script

注意:通常你会赋予它rwx rx rx权限,这对应于chmod 755 my_script

EDIT:

编辑:

can you create your own lets say .my_bashrc and somehow tell system to look in that file as well?

您可以创建自己的 .my_bashrc 并以某种方式告诉系统也查看该文件吗?

Yes you could, just tell your .bashrcto source your file:

是的,您可以,只需告诉您.bashrc源文件:

source ~/my_files/.my_bashrc

or

或者

. ~/my_files/.my_bashrc