向函数添加函数参数

问题描述

我有一个名为 auth函数,我想要函数参数,但我不知道该怎么做。函数参数为 usernamerepo。我试图用 bash 风格来做,但没有用,在线搜索也没有多大帮助。这是我目前拥有的。

function auth 
    username = $1
    repo = $2
    string = "git@github.com:${username}/${repo}"
    git remote set-url $string
end

我也试过

function auth 
    $username = $1
    $repo = $2
    $string = "git@github.com:$username/$repo"
    git remote set-url {$string}
end

但也没有用。错误发生在我设置变量 usernamestring,repo

~/.config/fish/functions/auth.fish (line 2): The expanded command was empty.
    $username = $1
    ^
in function 'auth' with arguments '1 2'
~/.config/fish/functions/auth.fish (line 3): The expanded command was empty.
    $repo = $2
    ^
in function 'auth' with arguments '1 2'
~/.config/fish/functions/auth.fish (line 5): The expanded command was empty.
    $string = "git@github.com:$username/$repo"
    ^

解决方法

Fish 将其参数存储在一个名为“$argv”的列表中,因此您想使用它。

在 fish 和 bash 中 $var = value 也是错误的语法。在 bash 中是

var=value

(没有 $= 周围没有空格)。

在鱼中

set var value

(也没有 $)。

所以你想要的是

function auth 
    set username $argv[1]
    set repo $argv[2]
    set string "git@github.com:$username/$repo"
    git remote set-url $string
end

但实际上,您想阅读https://github.com/whatwg/html/issues/954#issue-144165132,特别是the documentationthe section on $argv。这也应该可以通过在 fish 中简单地运行 help 来访问,这应该会在您的浏览器中打开一个本地副本。