如何覆盖bash命令?

Ale*_*ory 5 ssh bash

所以我基本上试图覆盖我的ssh命令所以我只需要键入ssh,默认情况下它将连接到我的主服务器.然后,如果我传递一个参数,说它username@server_port会运行基本命令.

# Fast SSH  (a working progress) TODO: make work without naming the function `fssh`
function fssh() {

    ALEX_SERVER_CONNECTION=$ALEX_SERVER_UNAME@$ALEX_SERVER_PORT

    # if the `ssh` argument is not set
    if [ -z "${1+xxx}" ]; then
        # echo "ALEX_SERVER_CONNECTION is not set at all";
        ssh $ALEX_SERVER_CONNECTION
    fi

    # if the `ssh` argument is set
    if [ -z "$1" ] && [ "${1+xxx}" = "xxx" ]; then
        ssh $1
    fi
}
Run Code Online (Sandbox Code Playgroud)

如何在没有f前面的情况下让它工作ssh

所以基本上这就是正确完成时的外观:

# Fast SSH
function ssh() {

    ALEX_SERVER_CONNECTION=$ALEX_SERVER_UNAME@$ALEX_SERVER_PORT

    # if the `ssh` argument is not set
    if [ -z "${1+xxx}" ]; then # ssh to the default server
        command ssh $ALEX_SERVER_CONNECTION
    fi

    # if the `ssh` argument is set
    if [ -z "$1" ] && [ "${1+xxx}" = "xxx" ]; then # ssh using a different server
        command ssh $1
    fi
}
Run Code Online (Sandbox Code Playgroud)

Édo*_*pez 6

您需要在函数中指定命令的绝对路径,ssh否则它将是递归的.例如,而不是:

function ssh() { ssh $USER@localhost; } # WRONG!
Run Code Online (Sandbox Code Playgroud)

你应该写:

function ssh() { command ssh $USER@localhost; }
Run Code Online (Sandbox Code Playgroud)

使用command内置的获得sshPATH(由@chepner的建议):

命令[-pVv]命令[arg ...]

  Run  command  with  args  suppressing  the normal shell function
  lookup. **Only builtin commands or commands found in the PATH  are
  executed**.
Run Code Online (Sandbox Code Playgroud)

为什么不别名?

使用函数是正确的模式,请阅读手册页中的" 别名和函数"部分.

ALIASES

在替换文本中没有使用参数的机制.如果需要参数,则应使用shell函数(参见下面的函数).

诊断

命名自定义函数时,ssh请执行以下操作:

  1. 一定要重新加载你的shell配置: source ~/.bashrc
  2. 检查是什么ssh:which sshtype ssh

typewhich

在声明自定义函数之前,我得到了:

type ssh  # ? ssh is /usr/bin/ssh
which ssh # ? /usr/bin/ssh
Run Code Online (Sandbox Code Playgroud)

宣布后function ssh() { ssh my-vm; },我得到:

which ssh # ? ssh () { ssh my-vm; }
type ssh  # ? ssh is a shell function
Run Code Online (Sandbox Code Playgroud)

建议

使用shbash语法:

  • sh:测试完成[ … ],便携但不强大;
  • bash测试完成[[ … ]],function关键字,便携性较差,但开发人员友好.