[英]How to use aliases defined in .bashrc in other scripts?
In ~/.bashrc, I defined some aliases.在 ~/.bashrc 中,我定义了一些别名。 But I cannot use them in other shell scripts, where I can only use aliases defined right there.
但是我不能在其他 shell 脚本中使用它们,在那里我只能使用在那里定义的别名。 Even though I sourced bashrc, it still did not work.
即使我使用了 bashrc,它仍然无法正常工作。 What should I do?
我该怎么办?
PS.附注。 I'm in bash.
我在狂欢。
除了采购~/.bashrc
之外,您还需要在脚本中执行shopt -s expand_aliases
。
The simplest answer is to do the 2 important things or it wont' work.最简单的答案是做两件重要的事情,否则就行不通。
#!/bin/bash -i
# Expand aliases defined in the shell ~/.bashrc
shopt -s expand_aliases
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.在此之后,您在 ~/.bashrc 中定义的别名将在您的 shell 脚本(giga.sh 或 any.sh)以及此类脚本中的任何函数或子 shell 中可用。
If you don't do that, you'll get an error:如果你不这样做,你会得到一个错误:
your_cool_alias: command not found
我遇到了这个问题,我用这个命令重新加载了文件来修复它。
$ source ~/.bashrc
Stolen from enzotib on ask ubuntu: Alias are deprecated in favor of shell functions.在询问 ubuntu 时从enzotib 窃取:别名已被弃用,以支持 shell 函数。 From
bash
manual page:从
bash
手册页:
For almost every purpose, aliases are superseded by shell functions.
对于几乎所有目的,别名都被 shell 函数取代。
To create a function, and export it to subshells, put the following in your ~/.bashrc
:要创建一个函数并将其导出到子shell,请将以下内容放入
~/.bashrc
:
petsc() {
~/petsc-3.2-p6/petsc-arch/bin/mpiexec "$@"
}
export -f petsc
Then you can freely call your command from your scripts.然后您可以从脚本中自由调用您的命令。
.bashrc
is meant for one purpose: to configure the environment for your interactive shells. .bashrc
仅用于一个目的:为交互式 shell 配置环境。 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.如果您希望在
.bashrc
和其他脚本之间共享代码,那么它属于一个单独的文件,该文件由每个.bashrc
和 shell 脚本提供。
There is a way of doing it globally without adding lines to each script you execute: by using the BASH_ENV
variable.有一种方法可以全局执行此操作,而无需向您执行的每个脚本添加行:使用
BASH_ENV
变量。
Here is my setup for OS X 10.8.5:这是我对 OS X 10.8.5 的设置:
/etc/launchd.conf: /etc/launchd.conf:
setenv BASH_ENV /Users/DK/.env
~/.bash_profile: ~/.bash_profile:
# == Bash setup for interactive shells ==
# === Environment for all shells ===
. $BASH_ENV
# [skipped]
~/.env: ~/.env:
# == Setup for all shells ==
# This is executed for all interactive and for non-interactive shells (e.g. scripts)
shopt -s expand_aliases extglob xpg_echo
# [skipped] Misc. variables and PATH setup
# === General aliases ===
alias pause='echo "Press [Return] or [Enter] to continue..."; read' # read -p does not display prompt in Eclipse console
# [skipped]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.