Multiple commands in an alias for bash

前端 未结 9 2005
[愿得一人]
[愿得一人] 2020-11-29 15:05

I\'d like to define an alias that runs the following two commands consecutively.

gnome-screensaver
gnome-screensaver-command --lock

Right

9条回答
  •  清酒与你
    2020-11-29 15:32

    Aliases are meant for aliasing command names. Anything beyond that should be done with functions.

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

    Aliases are names that are still associated with the original name. ll is just a slightly specific kind of ls.

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

    A function is a new command that has internal logic. It isn't simply a rename of another command. It does internal operations.

    Technically, aliases in the Bash shell language are so limited in capabilities that they are extremely ill suited for anything that involves more than a single command. Use them for making a small mutation of a single command, nothing more.

    Since the intention is to create a new command that performs an operation which internally will resolve in other commands, the only correct answer is to use a function here:

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

    Usage of aliases in a scenario like this runs into a lot of issues. Contrary to functions, which are executed as commands, aliases are expanded into the current command, which will lead to very unexpected issues when combining this alias "command" with other commands. They also don't work in scripts.

提交回复
热议问题