如何在其他脚本中使用.bashrc中定义的别名?
在 ~/.bashrc 中,我定义了一些别名。但我无法在其他 shell 脚本中使用它们,我只能使用在那里定义的别名。尽管我获取了 bashrc,但它仍然不起作用。我应该怎么办?
附言。我在狂欢。
In ~/.bashrc, I defined some aliases. But I cannot use them in other shell scripts, where I can only use aliases defined right there. Even though I sourced bashrc, it still did not work. What should I do?
PS. I'm in bash.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
除了获取
~/.bashrc
之外,您还需要在脚本中执行shopt -s Expand_aliases
操作。You need to do
shopt -s expand_aliases
in the script in addition to sourcing~/.bashrc
.最简单的答案是做两件重要的事情,否则它不会起作用。
此后,您在 ~/.bashrc 中定义的别名将在您的 shell 脚本(giga.sh 或 any.sh)以及此类脚本中的任何函数或子 shell 中可用。
如果你不这样做,你会得到一个错误:
The simplest answer is to do the 2 important things or it wont' work.
After this, your aliases that you have defined in ~/.bashrc they will be available in your shell script (giga.sh or any.sh) and to any function or child shell within such script.
If you don't do that, you'll get an error:
.bashrc
的目的只有一个:为交互式 shell 配置环境。如果您希望在.bashrc
和其他脚本之间共享代码,那么它属于一个单独的文件,该文件由.bashrc< 的每个来源。 /code> 和 shell 脚本。
.bashrc
is meant for one purpose: to configure the environment for your interactive shells. If you have code that you want shared between your.bashrc
and other scripts, then it belongs in a separate file that is sourced by each of your.bashrc
and shell script.我遇到了这个问题,我使用此命令重新加载了文件来修复它。
I had this problem and I reloaded the file with this command to fix it.
在 Ask ubuntu 上从 enzotib 窃取:别名已被弃用,转而使用 shell 函数。来自
bash
手册页:要创建函数并将其导出到子 shell,请将以下内容放入
~/.bashrc
中:然后您可以从脚本中自由调用命令。
Stolen from enzotib on ask ubuntu: Alias are deprecated in favor of shell functions. From
bash
manual page:To create a function, and export it to subshells, put the following in your
~/.bashrc
:Then you can freely call your command from your scripts.
有一种方法可以全局执行此操作,而无需向执行的每个脚本添加行:使用
BASH_ENV
变量。这是我对 OS X 10.8.5 的设置:
/etc/launchd.conf:
~/.bash_profile:
~/.env:
There is a way of doing it globally without adding lines to each script you execute: by using the
BASH_ENV
variable.Here is my setup for OS X 10.8.5:
/etc/launchd.conf:
~/.bash_profile:
~/.env: