如何创建一个永久的“别名”?

如果您创建别名,例如:

alias cls="clear" 

它存在,直到您终止终止会话。 当您启动新的终端窗口时,别名不再存在。 如何创建“永久”别名,每个终端会话中都存在一个?

您可以将这些别名放在~/.bash_aliases文件中。

该文件由~/.bashrc加载。 在Ubuntu 10.04上,需要取消注释以下行以启用~/.bash_aliases 。 在Ubuntu 11.04及更高版本中,它已经启用:

 if [ -f ~/.bash_aliases ]; then . ~/.bash_aliases fi 

别名命令将在任何新终端上可用。 要在任何现有终端上使用别名命令,需要从该终端获取~/.bashrc

 source ~/.bashrc 

将您的行添加到~/.bashrc~/.profile / ~/.bash_profile以进行远程登录。

如果要为所有用户执行命令,请将其放入/etc/bash.bashrc

编辑:在最新版本的Ubuntu中, ~/.bashrc自动提供~/.bash_aliases ,因此永久别名最好放入此文件中。

您可以将以下函数添加到.bashrc文件中。

 function permalias () { alias "$*"; echo alias "$*" >> ~/.bash_aliases } 

然后打开一个新终端或在当前终端中运行source ~/.bashrc 。 您现在可以使用permalias命令创建永久别名,例如permalias cls=clear

将该命令粘贴在~/.bash_profile的最后一行

有关~/.bash_profile~/.bashrc之间的区别,请参见http://www.joshstaiger.org/archives/2005/07/bash_profile_vs.html

每次打开一个新终端时都会运行~/.bashrc ,而~/.bash_profile则不会。 ~/.bashrc包含以下内容,其中包含~/.bash_aliases文件。 这将是添加别名的最合适位置。

 # Alias definitions. # You may want to put all your additions into a separate file like # ~/.bash_aliases, instead of adding them here directly. # See /usr/share/doc/bash-doc/examples in the bash-doc package. if [ -f ~/.bash_aliases ]; then . ~/.bash_aliases fi 
 reset echo "Enter alias like this:" echo "alias dir='ls'" read var echo "$var" >> /home/$user/.bashrc && . ~/.bashrc cat .bashrc