我想定义一个别名,连续运行以下两个命令。

gnome-screensaver
gnome-screensaver-command --lock

现在我添加了

alias lock='gnome-screensaver-command --lock'

到我的.bashrc,但由于我经常锁定我的工作站,只输入一个命令会更容易。


当前回答

function lock() {
    gnome-screensaver
    gnome-screensaver-command --lock
}

上面的代码在bash中翻译得很好:

bottom() {
    clear
    printf '\n%.0s' {1..100}
}
alias c="bottom"

All I wanted to do was clear the screen (c alias) and have the bash prompt appear at the bottom, not top of terminal window. I had solved this long ago (too long ago... forgot what I did), but now I've put the function in .bash_profile and it's off to the races! For now, I am also executing the function so that when I open a new term. window, the prompt, and only the prompt, appears at the bottom. Thanks much for the suggestion. I'm not sure if I just miss this kind of stuff or miss getting paid for it... probably both. :-)

其他回答

在11岁的讨论中加入我的2点意见,试试这个:

别名锁="gnome-screensaver \gnome-screensaver-command——lock"

别名用于使命令名别名化。除此之外的任何事情都应该用函数来完成。

alias ll='ls -l' # The ll command is an alias for ls -l

别名是仍然与原来的名称相关联的名称。Ll是ls的一种特殊形式。

d() {
    if exists colordiff; then
        colordiff -ur "$@"
    elif exists diff; then
        diff -ur "$@"
    elif exists comm; then
        comm -3 "$1" "$2"
    fi | less
}

函数是具有内部逻辑的新命令。它不仅仅是另一个命令的重命名。它做内部操作。

从技术上讲,Bash shell语言中的别名在功能上非常有限,以至于它们非常不适合涉及多个命令的任何事情。使用它们对单个命令进行小的修改,仅此而已。

由于目的是创建一个新命令,执行内部将在其他命令中解析的操作,所以唯一正确的答案是在这里使用函数:

lock() {
    gnome-screensaver
    gnome-screensaver-command --lock
}

在这样的场景中使用别名会遇到很多问题。与作为命令执行的函数相反,别名被扩展到当前命令中,这将导致在将别名“命令”与其他命令组合时出现非常意想不到的问题。它们也不能在脚本中工作。

这样不行吗?

alias whatever='gnome-screensaver ; gnome-screensaver-command --lock'

将此函数添加到~/。并重新启动终端或运行source ~/.bashrc

function lock() {
    gnome-screensaver
    gnome-screensaver-command --lock
}

这样,当您在终端中输入lock时,这两个命令就会运行。

在您的特定情况下,创建别名可能有用,但我不建议这样做。直观地说,我们会认为别名的值运行起来与在终端中输入值是一样的。然而事实并非如此:

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

and

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

所以除非迫不得已,不要使用别名。 https://ss64.com/bash/alias.html

function lock() {
    gnome-screensaver
    gnome-screensaver-command --lock
}

上面的代码在bash中翻译得很好:

bottom() {
    clear
    printf '\n%.0s' {1..100}
}
alias c="bottom"

All I wanted to do was clear the screen (c alias) and have the bash prompt appear at the bottom, not top of terminal window. I had solved this long ago (too long ago... forgot what I did), but now I've put the function in .bash_profile and it's off to the races! For now, I am also executing the function so that when I open a new term. window, the prompt, and only the prompt, appears at the bottom. Thanks much for the suggestion. I'm not sure if I just miss this kind of stuff or miss getting paid for it... probably both. :-)