.bashrc文件
In my recent post about setting up Ubuntu with Bash scripts, I briefly alluded to the magic of .bashrc
. This didn’t really do it justice, so here’s a quick post that offers a bit more detail about what the Bash configuration file can do.
在我最近的有关使用Bash脚本设置Ubuntu的帖子中 ,我简短地提到了.bashrc
的魔力。 这样做并没有真正做到公平,所以这里有一篇快速文章,提供了有关Bash配置文件可以做什么的更多详细信息。
My current configuration hugely improves my workflow, and saves me well over 50% of the keystrokes I would have to employ without it! Let’s look at some examples of aliases, functions, and prompt configurations that can improve our workflow by helping us be more efficient with fewer key presses.
我当前的配置极大地改善了我的工作流程,并且为我节省了超过50%的键击操作,而如果没有它,我将不得不使用它! 让我们看一些别名,函数和提示配置的示例,这些示例可以通过减少按键次数来提高效率来改善工作流程。
A smartly written .bashrc
can save a whole lot of keystrokes. We can take advantage of this in the literal sense by using bash aliases, or strings that expand to larger commands. For an indicative example, here is a Bash alias for copying files in the terminal:
精巧地编写.bashrc
可以节省大量的击键。 通过使用bash别名或扩展为较大命令的字符串,我们可以从字面意义上利用此优势。 作为说明性示例,这是用于在终端中复制文件的Bash别名:
# Always copy contents of directories (r)ecursively and explain (v) what was done
alias cp='cp -rv'
The alias
command defines the string we’ll type, followed by what that string will expand to. We can override existing commands like cp
above. On its own, the cp
command will only copy files, not directories, and succeeds silently. With this alias, we need not remember to pass those two flags, nor cd
or ls
the location of our copied file to confirm that it’s there! Now, just those two key presses (for c
and d
) will do all of that for us.
alias
命令定义了我们将键入的字符串,然后是该字符串将扩展为的字符串。 我们可以覆盖上面的cp
等现有命令。 cp
命令本身将仅复制文件,而不复制目录,并且以静默方式成功执行。 使用该别名,我们不必记住传递这两个标志,也不必cd
或ls
复制文件的位置来确认它是否存在! 现在,只有这两个按键(对于c
和d
)将为我们完成所有这些操作。
Here are a few more .bashrc
aliases for passing flags with common functions.
以下是一些.bashrc
别名,用于通过常用功能传递标志。
# List contents with colors for file types, (A)lmost all hidden files (without . and ..), in (C)olumns, with class indicators (F)
alias ls='ls --color=auto -ACF'
# List contents with colors for file types, (a)ll hidden entries (including . and ..), use (l)ong listing format, with class indicators (F)
alias ll='ls --color=auto -alF'
# Explain (v) what was done when moving a file
alias mv='mv -v'
# Create any non-existent (p)arent directories and explain (v) what was done
alias mkdir='mkdir -pv'
# Always try to (c)ontinue getting a partially-downloaded file
alias wget='wget -c'
Aliases come in handy when we want to avoid typing long commands, too. Here are a few I use when working with Python environments:
当我们也希望避免键入长命令时,别名会派上用场。 以下是在Python环境中使用的一些方法:
alias pym='python3 manage.py'
alias mkenv='python3 -m venv env'
alias startenv='source env/bin/activate && which python3'
alias stopenv='deactivate'
For further inspiration on ways Bash aliases can save time, I highly recommend the examples in this article.
为了进一步启发Bash别名可以节省时间,我强烈推荐本文中的示例 。
One downside of the aliases above is that they’re rather static - they’ll always expand to exactly the text declared. For a Bash alias that takes arguments, we’ll need to create a function. We can do this like so:
上面的别名的一个缺点是它们相当静态-它们将始终扩展到所声明的文本。 对于带有参数的Bash别名,我们需要创建一个函数。 我们可以这样做:
# Show contents of the directory after changing to it
function cd () {
builtin cd "$1"
ls -ACF
}
I can’t begin to tally how many times I’ve typed cd
and then ls
immediately after to see the contents of the directory I’m now in. With this function set up, it all happens with just those two letters! The function takes the first argument, $1
, as the location to change directory to, then prints the contents of that directory in nicely formatted columns with file type indicators. The builtin
part is necessary to get Bash to allow us to override this default command.
我不能开始统计输入cd
,然后立即输入ls
来查看我现在所在目录的内容。设置此功能后,所有这两个字母都会发生! 该函数将第一个参数$1
作为更改目录的位置,然后将该目录的内容打印在格式良好的列中,并带有文件类型指示符。 为了使Bash能够覆盖此默认命令, builtin
部分是必需的。
Bash functions are very useful when it comes to downloading or upgrading software, too. I previously spent at least a few minutes every couple weeks downloading the new extended version of the static site generator Hugo, thanks to their excellent shipping frequency. With a function, I only need to pass in the version, and the upgrade happens in a few seconds.
Bash功能在下载或升级软件时也非常有用。 由于以前的发布频率很高,我以前每两周至少花费几分钟来下载静态站点生成器Hugo的新扩展版本。 有了功能,我只需要传递版本,升级就会在几秒钟内完成。
# Hugo install or upgrade
function gethugo () {
wget -q -P tmp/ https://github.com/gohugoio/hugo/releases/download/v"$@"/hugo_extended_"$@"_Linux-64bit.tar.gz
tar xf tmp/hugo_extended_"$@"_Linux-64bit.tar.gz -C tmp/
sudo mv -f tmp/hugo /usr/local/bin/
rm -rf tmp/
hugo version
}
The $@
notation simply takes all the arguments given, replacing its spot in the function. To run the above function and download Hugo version 0.57.2, we use the command gethugo 0.57.2
.
$@
表示法只是接受给定的所有参数,替换其在函数中的位置。 要运行上述功能并下载Hugo版本0.57.2,请使用命令gethugo 0.57.2
。
I’ve got one for Golang, too:
我也为Golang买了一个:
function getgolang () {
sudo rm -rf /usr/local/go
wget -q -P tmp/ https://dl.google.com/go/go"$@".linux-amd64.tar.gz
sudo tar -C /usr/local -xzf tmp/go"$@".linux-amd64.tar.gz
rm -rf tmp/
go version
}
Or how about a function that adds a remote origin URL for GitLab to the current repository?
还是将GitLab的远程原始URL添加到当前存储库的函数呢?
function glab () {
git remote set-url origin --add [email protected]:"$@"/"${PWD##*/}".git
git remote -v
}
With glab username
, we can create a new origin
URL for the current Git repository with our username
on GitLab.com. Pushing to a new remote URL automatically creates a new private GitLab repository, so this is a useful shortcut for creating backups!
随着glab username
,我们可以创建一个新的origin
为当前的Git仓库与我们的URL username
上GitLab.com。 推送到新的远程URL会自动创建一个新的私有GitLab存储库 ,因此这是创建备份的有用快捷方式!
Bash functions are really only limited by the possibilities of scripting, of which there are, practically, few limits. If there’s anything we do on a frequent basis that requires typing a few lines into a terminal, we can probably create a Bash function for it!
Bash函数实际上仅受脚本编写可能性的限制,实际上几乎没有限制。 如果我们经常需要在终端上输入几行内容,我们可以为其创建一个Bash函数!
Besides directory contents, it’s also useful to see the full path of the directory we’re in. The Bash prompt can show us this path, along with other useful information like our current Git branch. To make it more readable, we can define colours for each part of the prompt. Here’s how we can set up our prompt in .bashrc
to accomplish this:
除了目录内容外,查看我们所在目录的完整路径也很有用。Bash提示符可以向我们显示此路径,以及其他有用的信息,例如当前的Git分支。 为了使其更具可读性,我们可以为提示的每个部分定义颜色。 我们可以在.bashrc
设置提示来完成此操作:
# Colour codes are cumbersome, so let's name them
txtcyn='\[\e[0;96m\]' # Cyan
txtpur='\[\e[0;35m\]' # Purple
txtwht='\[\e[0;37m\]' # White
txtrst='\[\e[0m\]' # Text Reset
# Which (C)olour for what part of the prompt?
pathC="${txtcyn}"
gitC="${txtpur}"
pointerC="${txtwht}"
normalC="${txtrst}"
# Get the name of our branch and put parenthesis around it
gitBranch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
# Build the prompt
export PS1="${pathC}\w ${gitC}\$(gitBranch) ${pointerC}\$${normalC} "
Result:
结果:
~/github/myrepo (master) $
Naming the colours helps to easily identify where one colour starts and stops, and where the next one begins. The prompt that we see in our terminal is defined by the string following export PS1
, with each component of the prompt set with an escape sequence. Let’s break that down:
命名颜色有助于轻松识别一种颜色的起点和终点,以及另一种颜色的起点。 我们在终端中看到的提示是由export PS1
的字符串定义的,提示的每个组件都设置有转义序列 。 让我们分解一下:
\w
displays the current working directory,
\w
显示当前工作目录,
\$(gitBranch)
calls the gitBranch
function defined above, which displays the current Git branch,
\$(gitBranch)
调用上面定义的gitBranch
函数,该函数显示当前的Git分支,
\$
will display a “$” if you are a normal user or in normal user mode, and a “#” if you are root.
如果您是普通用户或处于普通用户模式, \$
将显示“ $”,如果您是root用户,则\$
将显示“#”。
The full list of Bash escape sequences can help us display many more bits of information, including even the time and date! Bash prompts are highly customizable and individual, so feel free to set it up any way you please.
Bash转义序列的完整列表可以帮助我们显示更多信息,甚至包括时间和日期! Bash提示是高度可定制的且个性化的,因此可以随意设置它。
Here are a few options that put information front and centre and can help us to work more efficiently.
这里有一些选择可以使信息处于领先地位,并可以帮助我们更有效地工作。
Username and current time with seconds, in 24-hour HH:MM:SS format:
用户名和当前时间(以秒为单位),格式为24小时HH:MM:SS:
export PS1="${userC}\u ${normalC}at \t >"
user at 09:35:55 >
Full file path on a separate line, and username:
完整文件路径放在单独的行上,并提供用户名:
export PS1="${pathC}\w${normalC}\n\u:"
~/github/myrepo
user:
export PS1=">"
>
We can build many practical prompts with just the basic escape sequences; once we start to integrate functions with prompts, as in the Git branch example, things can get really complicated. Whether this amount of complication is an addition or a detriment to your productivity, only you can know for sure!
我们可以使用基本的转义序列来构建许多实用的提示。 一旦我们开始将功能与提示集成在一起,例如在Git分支示例中,事情就会变得非常复杂。 无论这种复杂程度是增加还是损害了您的生产率,只有您才能确定!
Many fancy Bash prompts are possible with programs readily available with a quick search. I’ve intentionally not provided samples here because, well, if you can tend to get as excited about this stuff as I can, it might be a couple hours before you get back to what you were doing before you started reading this post, and I just can’t have that on my conscience.
快速搜索容易获得的程序可能会出现许多精美的Bash提示。 我故意没有在这里提供示例,因为,好吧,如果您可能会尽可能地对此东西感到兴奋,那么可能需要几个小时才能回到开始阅读的内容之前,然后我只是出于我的良心而已。
We’ve hopefully struck a nice balance now between time invested and usefulness gained from our Bash configuration file! I hope you use your newly-recovered keystroke capacity for good.
希望我们现在在投入的时间和从Bash配置文件获得的有用性之间找到了一个不错的平衡! 希望您永久使用新恢复的击键容量。
翻译自: https://www.freecodecamp.org/news/how-to-do-twice-as-much-with-half-the-keystrokes-using-bashrc/
.bashrc文件