如何覆盖bash命令?

时间:2014-08-20 07:29:58

标签: bash ssh

所以我基本上试图覆盖我的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
}

如果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
}

3 个答案:

答案 0 :(得分:5)

解决方案

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

function ssh() { ssh $USER@localhost; } # WRONG!

你应该写:

function ssh() { command ssh $USER@localhost; }

使用command内置功能从ssh获取PATH(由@chepner建议):

  

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

  Run  command  with  args  suppressing  the normal shell function
  lookup. **Only builtin commands or commands found in the PATH  are
  executed**.

为什么不使用Alias?

使用功能是正确的模式,请阅读Aliases and Functions sections from the man page

  

<强> ALIASES

     

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

诊断

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

  1. 请务必重新加载您的shell配置:source ~/.bashrc
  2. 使用sshwhich ssh
  3. 检查type ssh是什么

    typewhich

    在宣布自定义函数之前,我得到了:

    type ssh  # → ssh is /usr/bin/ssh
    which ssh # → /usr/bin/ssh
    

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

    which ssh # → ssh () { ssh my-vm; }
    type ssh  # → ssh is a shell function
    

    通知书

    使用shbash语法:

    • sh:使用[ … ]进行测试,便携但不强大;
    • bash测试已完成[[ … ]]function关键字,不太便于携带,但对开发人员友好。

答案 1 :(得分:2)

  

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

~/.bashrc中设置别名:

alias ssh='fssh'

答案 2 :(得分:0)

假设您的脚本名为fssh且可执行,您只需:

alias ssh='fssh'

.bashrc