【问题标题】:How to overwrite a bash command?如何覆盖bash命令?
【发布时间】:2014-08-20 07:29:57
【问题描述】:

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

如果没有fssh 前面,我如何让它工作?

所以基本上这就是正确完成后的样子:

# 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
}

【问题讨论】:

  • 我在想如果我包含定义ssh 的路径,我可以包含source /path/to/ssh 之类的东西,它可能会起作用,但我找不到正确的尝试路径。
  • 如果有错误信息可以提供吗?你把你的函数放在~/.bashrc了吗?
  • @AlexCory 你能澄清你的目标是什么,因为它是模棱两可的,会导致不同的答案

标签: bash ssh


【解决方案1】:

解决方案

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

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

你应该写:

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

使用内置的commandPATH 获取ssh(由@chepner 建议):

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

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

为什么不用别名?

使用函数是正确的模式,阅读Aliases and Functions sections from the man page

别名

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

诊断

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

  1. 一定要重新加载你的shell配置:source ~/.bashrc
  2. 检查ssh 是什么:which sshtype 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 关键字,不太便携但对开发人员友好。

【讨论】:

  • 代替ssh 的绝对路径,您还可以使用command 内置函数,它保留了进行路径查找的能力,同时避免了对函数的递归调用。 function ssh() { command ssh $USER@localhost; }
【解决方案2】:

如果没有 ssh 前面的 f,我如何让它工作?

~/.bashrc中设置别名:

alias ssh='fssh'

【讨论】:

  • 他为什么需要别名?功能还不错
  • 他已经有了fssh 函数。别名是给 OP 的 fssh 函数取另一个名字。
  • 是的,正如第一行所述,他尝试“覆盖我的 ssh”,对脚本第一行的评论表明他不想将函数命名为 fssh
  • 给函数命名是 OP 的选择,确保它也可以重命名为 ssh 或者只是别名。
【解决方案3】:

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

alias ssh='fssh'

在你的.bashrc

【讨论】:

  • 一种解决方案可能是将代码复制/粘贴到脚本fssh 中,去掉function 声明,使用chmod +x fssh 使其可执行,并且别名将起作用。
  • 为什么是外部脚本?如果您利用alias 机制,您也可以利用functions,那么为什么还要为用户范围的自定义而使用外部脚本呢?
  • 我不明白这有什么问题,我觉得更方便地可视化您的自定义并切换它。
猜你喜欢
  • 2021-06-26
  • 2020-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多