如何为终端线路设置别名?

Phi*_*ego 9 command-line bash alias

我想轻松地git-go为此终端行设置别名:

git commit -m "init "; git push; git status
Run Code Online (Sandbox Code Playgroud)

所以当我输入 git-go 时,应该输入这一行。

我怎样才能做到这一点?我看到的答案仅涵盖没有参数的命令的别名。但我想为任意终端线设置别名。

编辑: 我学会了使用函数而不是别名,因为

有关别名的定义和使用的规则有些令人困惑。

对于几乎所有用途,shell 函数都比别名更受欢迎。

所以除非必须,否则不要使用别名。 https://ss64.com/bash/alias.html

Eli*_*gan 13

您可以像设置任何别名一样执行此操作。

alias git-go='git commit -m "init "; git push; git status'
Run Code Online (Sandbox Code Playgroud)

它变得棘手的情况不是当别名运行命令并将参数传递给该命令时,甚至当别名运行多个由 分隔的命令时;,而是当您希望别名接受并使用其自己的命令行参数时.

例如,您该别名之后写的任何内容都将粘贴到末尾,从而作为命令行参数传递给第三个git命令,在git status. (实际上并不是将以下文本粘贴到末尾,而是将以下文本单独保留并用其定义替换别名。)

所以你可以不带参数运行你的别名,这是有效的,最后一个命令是git status

git-go
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用要传递给的参数运行它git status。例如,当您以这种方式运行它时,最后一个命令是git-status --show-stash

git-go --show-stash
Run Code Online (Sandbox Code Playgroud)

什么,你不能在Bash中(和其他的Bourne风格的贝壳)的别名要做的就是让别名接受命令行参数,并将它们比其他地方结束。

例如,假设您想git-go接受它用于提交消息的参数。你不能把它写成别名。解决方案是将其编写为 shell 函数:

git-go() { git commit -m "$1"; git push; git status; }
Run Code Online (Sandbox Code Playgroud)

在 shell 函数的定义中,位置参数$1$2等保存传递给 shell 函数的命令行参数的值。别名没有与此对应的功能,因为别名扩展实际上是一种宏处理形式,在 shell 解析命令时很早就发生了。

当然,即使您不需要在定义中使用位置参数,您也可以将其编写为 shell 函数,正如Videonauth 建议的那样


Vid*_*uth 10

您可以在~/.bash_aliases文件中将其声明为一个函数,如下所示:

git-go(){
    git commit -m "init "
    git push
    git status
}
Run Code Online (Sandbox Code Playgroud)

或者您可以在同一个文件中创建别名,如下所示:

alias git-go='git commit -m "init "; git push; git status'
Run Code Online (Sandbox Code Playgroud)

. ~/.bash_aliases更改后不要忘记重新打开终端或获取文件 ( )。