什么是 .bashrc，为什么要编辑 .bashrc？
.bashrc
![](/data/attachment/album/201801/31/145506vz6pxrtzqoxtmgou.png)


你的 home 目录下藏着很多隐藏文件。如果你在运行 macOS 或者主流的 Linux 发行版的话，你就会在靠近隐藏文件列表的上方看见一个名为 `.bashrc` 的文件。那么什么是 `.bashrc`，编辑 `.bashrc` 又有什么用呢？


![finder-find-bashrc](/data/attachment/album/201801/31/145506am14t1jmx4tjzq17.png "finder-find-bashrc")


如果你运行一个基于 Unix 或者类 Unix 的操作系统，bash 很有可能是作为默认终端被安装的。虽然存在很多[不同的 shell](https://www.maketecheasier.com/alternative-linux-shells/)，bash 却是最常见或许也是最主流的。如果你不明白那意味着什么，bash 是一个能解释你输入进终端程序的东西，并且基于你的输入来运行命令。它在一定程度上支持使用脚本来定制功能，这时候就要用到 `.bashrc` 了。


为了加载你的配置，bash 在每次启动时都会加载 `.bashrc` 文件的内容。每个用户的 home 目录都有这个 shell 脚本。它用来存储并加载你的终端配置和环境变量。


终端配置可以包含很多不同的东西。最常见的，`.bashrc` 文件包含用户想要用的别名。别名允许用户通过更短的名字或替代的名字来指向命令，对于经常在终端下工作的人来说这可是一个省时利器。


![terminal-edit-bashrc-1](/data/attachment/album/201801/31/145507bxspgcpiizi4nnng.png "terminal-edit-bashrc-1")


你可以在任何终端文本编辑器上编辑 `.bashrc`。在接下来的例子中我们将使用 `nano`。


要使用 `nano` 来编辑 `.bashrc`，在终端中调用以下命令：



```
nano ~/.bashrc

```

如果你之前从没有编辑过 `.bashrc` 的话，你也许会发现它是空的。这没关系！如果不是的话，你可以随意在任一行添加你的配置。


你对 bashrc 所做的任何修改将在下一次启动终端时生效。如果你想立刻生效的话，运行下面的命令：



```
source ~/.bashrc

```

你可以添加到任何 `.bashrc` 的位置，随意使用命令（通过 `#`）来组织你的代码。


编辑 `.bashrc` 需要遵循 [bash 脚本格式](http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html)。如果你不知道如何用 bash 编写脚本的话，有很多在线资料可供查阅。这是一本相当全面的[介绍指南](https://www.digitalocean.com/community/tutorials/an-introduction-to-useful-bash-aliases-and-functions)，包含一些我们没能在这里提及的 bashrc 的方面。


**相关**： [如何在 Linux 启动时以 root 权限运行 bash 脚本](https://www.maketecheasier.com/run-bash-script-as-root-during-startup-linux/ "How to Run Bash Script as Root During Startup on Linux")


有一些有用的小技巧能使你的终端体验将更高效，也更用户友好。


### 为什么我要编辑 bashrc ？


#### Bash 提示符


bash 提示符允许你自定义你的终端，并让它在你运行命令时显示提示。自定义的 bash 提示符着实能提高你在终端的工作效率。


看看这些即[有用](https://www.maketecheasier.com/8-useful-and-interesting-bash-prompts/)又[有趣](https://www.maketecheasier.com/more-useful-and-interesting-bash-prompts/)的 bash 提示符，你可以把它们添加到你的 `.bashrc` 里。


#### 别名


![terminal-edit-bashrc-3](/data/attachment/album/201801/31/145509t7n1tnnqwnnn6tnn.png "terminal-edit-bashrc-3")


别名允许你使用简写的代码来执行你想要的某种格式的某个命令。让我们用 `ls` 命令来举个例子吧。`ls` 命令默认显示你目录里的内容。这挺有用的，不过显示目录的更多信息，或者显示目录下的隐藏内容，往往更加有用。因此，有个常见的别名就是 `ll`，用来运行 `ls -lha` 或者其他类似的命令。这样就能显示文件的大部分信息，找出隐藏的文件，并能以“能被人类阅读”的单位显示文件大小，而不是用“块”作为单位。


你需要按照下面这样的格式书写别名：



```
alias ll = "ls -lha"

```

左边输入你想设置的别名，右边引号里是要执行的命令。你可以用这种方法来创建命令的短版本，防止出现常见的拼写错误，或者让一个命令总是带上你想要的参数来运行。你也可以用你喜欢的缩写来规避讨厌或容易忘记的语法。这是一些[常见的别名的用法](https://www.maketecheasier.com/install-software-in-various-linux-distros/#aliases)，你可以添加到你的 `.bashrc` 里。


#### 函数


![terminal-edit-bashrc-2](/data/attachment/album/201801/31/145509hbz59nzan249fs95.png "terminal-edit-bashrc-2")


除了缩短命令名，你也可以用 bash 函数组合多个命令到一个操作。这些命令可以很复杂，但是它们大多遵循这种语法：



```
function_name () {
 command_1
 command_2
}

```

下面的命令组合了 `mkdir` 和 `cd` 命令。输入 `md folder_name` 可以在你的工作目录创建一个名为“folder\_name”的目录并立刻导航进入。



```
md () {
  mkdir -p $1
  cd $1 
}

```

如你所见，函数中的 `$1` 代表第一个参数，就是你在函数名后紧跟着输入的文本。


### 总结


不像某些自定义终端的方法，变动 bashrc 是非常直接且低风险的。即使你一不小心全搞砸了，你也可以随时删掉 bashrc 文件然后重新来一遍。试试看吧，你会惊叹于你提高的生产力的。




---


via: <https://www.maketecheasier.com/what-is-bashrc/>


作者：[Alexander Fox](https://www.maketecheasier.com/author/alexfox/) 译者：[heart4lor](https://github.com/heart4lor) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
![A photograph of an Ubuntu terminal prompt.](https://www.maketecheasier.com/assets/uploads/2023/04/edit-bashrc-linux-00-featured-image.jpg)

There are a number of hidden files tucked away in your home directory. If you run macOS or a popular Linux distribution, you’ll see the “.bashrc” file near the top of your hidden files. This guide explains what the .bashrc file does and why you should edit and customize it.

## What Is .bashrc?

If you run a Unix-based or Unix-like operating system, you likely have bash installed as your default terminal. While many [different shells](https://www.maketecheasier.com/alternative-linux-shells/) exist, bash is both the most common and, likely, the most popular. If you don’t know what that means, bash interprets your typed input in the Terminal program and runs commands based on your input. It allows for some degree of customization using scripting, which is where .bashrc comes in.

![finder-find-bashrc A screenshot of the bashrc file inside a file manager.](https://www.maketecheasier.com/assets/uploads/2023/04/edit-bashrc-linux-01-bashrc-file-nautilus.png)

The .bashrc file contains a list of customization options for the bash shell and is loaded at each launch. The .bashrc file is found in the Home user directory. The . (dot) in front of the file name means that it is hidden from plain view. You will need to activate the “View Hidden Files” option to view it.

## How Can I Edit .bashrc?

You can edit .bashrc in any text editor. You can also use [nano](https://www.maketecheasier.com/linux-nano-text-editor-beginner-guide/) to edit it in the Terminal.

nano ~/.bashrc

If you have not edited your .bashrc file before, you may find that it’s empty. That’s fine! If not, feel free to put your additions on any line.

Edits in .bashrc have to follow [bash’s scripting format](https://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html). If you don’t know how to script with bash, there are a number of online resources. This guide represents a beginner-friendly introduction into the [aspects of Bash that are not mentioned here](https://www.maketecheasier.com/beginners-guide-scripting-linux/).

Any changes you make to .bashrc will be applied the next time you launch the terminal. If you want to apply them immediately, run the command below:

source ~/.bashrc

**Note**: you can add to .bashrc wherever you would like, but feel free to use comment (lines preceded by `#`

) to document your code.

## .bashrc Customization Tips

There are a couple of useful tricks to make your terminal experience more efficient and user-friendly.

### 1. Aliases

Aliases allow you to create a shorter version of a long command.

For example, [the command ls](https://www.maketecheasier.com/linux-ls-commands/) is often used to display the contents of your directory. You can also use `ls -lha`

to display the content with more detail. Now there is an alias `ll`

, which is set to run `ls -lha`

. Just type `ll`

in the terminal, and it will run the `ls -lha`

command.

![terminal-edit-bashrc-3 A terminal showing a list of basic aliases.](https://www.maketecheasier.com/assets/uploads/2023/04/edit-bashrc-linux-03-sample-alias-list.png)

You’ll need to format your aliases like so:

alias ll="ls -lha"

Type the text you want to replace on the left and the command on the right between quotes. Use this to create shorter versions of the command, guard against common typos, or force a command to always run with your favored flags. You can also circumvent annoying or easy-to-forget syntax with your own preferred shorthand.

### 2. Functions

In addition to shorthand command names, you can combine multiple commands into a single operation using bash functions. They can get pretty complicated, but they generally follow this syntax:

function_name () { command_1 command_2 }

For example, the command below combines `mkdir`

and `cd`

. Typing `md folder_name`

creates a directory named “folder_name” in your working directory and navigates there immediately.

md () { mkdir -p $1 cd $1 }

The `$1`

you see in the function represents the first argument, which is the text you type immediately after the function name.

### 3. Adding a Simple Bash Prompt

You can also use the .bashrc file to create a custom shell prompt. The shell prompt is a line of text that shows up at the start of every terminal input line. This can contain either static information, such as your system’s name or dynamic scripts that change depending on the shell’s current working directory.

Here are several [interesting bash prompts](https://www.maketecheasier.com/8-useful-and-interesting-bash-prompts/) you can add to your .bashrc file.

### 4. Modify the PATH Variable

The PATH variable is an important variable that tells your shell where to find scripts and binaries for the current session. You can use the .bashrc file to store/change the content of your PATH variable. This is useful in cases where you want to run your own programs from a custom directory.

To modify the PATH variable, add the following line of code to the end of your .bashrc:

PATH="$PATH:"

This will tell your shell to load the default value of PATH before loading any custom arguments.

![A screenshot showing the PATH variable referencing itself.](https://www.maketecheasier.com/assets/uploads/2023/04/edit-bashrc-linux-12-path-variable-import-system-default.png)

Now add your own directories to the end of this PATH variable.

PATH=":/home/$USER/bin:/home/$USER/git"

![A screenshot showing a PATH variable with custom directories.](https://www.maketecheasier.com/assets/uploads/2023/04/edit-bashrc-linux-13-path-variable-add-custom-path.png)

### 5. Exporting New Environment Variables

Environment variables are containers that hold session-specific values for a program or system process. It contains strings that give programs either an option or a resource that it can use while running.

For example, some programs use the “POSTGRESQL_DATABASE” environment variable when they link to an external database process:

POSTGRESQL_DATABASE="postgres://ramces:password@localhost:5432/db"

![A screenshot showing a custom environment variable.](https://www.maketecheasier.com/assets/uploads/2023/04/edit-bashrc-linux-17-sample-custom-environment-variable.png)

Export the variable to your shell. This will convert it from a regular shell variable to an environment variable:

POSTGRESQL_DATABASE="postgres://ramces:password@localhost:5432/db" export POSTGRESQL_DATABASE

![A screenshot showing the export command and the new environment variable.](https://www.maketecheasier.com/assets/uploads/2023/04/edit-bashrc-linux-18-export-environment-variable.png)

### 6. Linking .bashrc with .bash_profile

The difference between .bashrc and .bash_profile is one of the biggest points of confusion for a novice Linux user. bash_profile only runs once during login, while .bashrc runs whenever a new shell starts.

However, this murky division means that it is possible to mix up the two and fail to run the command that you want to run. One quick way to solve this issue is by ensuring that .bashrc runs as soon as .bash_profile loads.

Add the following line of code to the end of the .bashrc file:

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

![A terminal showing a basic if statement in bash_profile.](https://www.maketecheasier.com/assets/uploads/2023/04/edit-bashrc-linux-21-basic-bash-profile-configuration.png)

This small block of code will tell the shell to check whether a .bashrc file exists in your home directory. If it finds one, Bash will load the file and run its commands in the current shell instance.

**Good to know: **while Bash is often used as a terminal interface for your system, you can also [use Python to automate your computing tasks](https://www.maketecheasier.com/useful-python-one-liners/).

## Frequently Asked Questions

### Will my .bashrc file work with other Linux shells?

The developers of Bash designed the .bashrc file to work only with the Bash shell. However, it is important to note that most of the commands inside a .bashrc file are cross-compatible with some Unix-like shells. For example, you can copy the contents of a .bashrc file to its Korn shell counterpart, .kshrc, and it will still work.

### Is it possible to set my default file permissions using Bash?

Yes. To do this, you need to add the `umask`

command at the end of your .bashrc file. This is a simple program that sets the bit mask on the permission bits that you want to set. For example, the command `umask 027`

is the equivalent of running `sudo chmod -R 750 ./directory`

.

Image credit: [Unsplash](https://unsplash.com/photos/xbEVM6oJ1Fs). All alterations and screenshots by Ramces Red.

Our latest tutorials delivered straight to your inbox