有没有办法将函数中的所有参数粘贴在一行中?

her*_*ity 0 shell bash shell-script

我现在有这在我的.bashrc,因为我使用git status和git diff频繁。我希望能够读取可能作为选项传入的其他条目,例如-swith git diff. 我怎样才能在函数而不是别名中做到这一点?我只知道这$#会给我传入的参数数量,但是status在第 48 行说完之后如何粘贴所有参数?

 42 # =========================================================
 43 #                         Git
 44 # =========================================================
 45 g () {
 46   case $1 in
 47     "s")
 48       git status
 49       ;;
 50     "d")
 51       git diff
 52       ;;
 53   esac
 54 }
Run Code Online (Sandbox Code Playgroud)

Ste*_*itt 6

"$@" 将被正确引用的所有参数替换,因此在移动以删除子命令快捷方式后:

g () {
  cmd=$1
  shift
  case "$cmd" in
    s) git status "$@" ;;
    d) git diff "$@" ;;
  esac
}
Run Code Online (Sandbox Code Playgroud)

不过,我建议使用git别名,而不是这样做;设置上述内容:

git alias s status
git alias d diff
Run Code Online (Sandbox Code Playgroud)

或者,如果您没有git-alias(通常在git-extras),

git config --global alias.s status
git config --global alias.d diff
Run Code Online (Sandbox Code Playgroud)

(您只需执行此操作一次,别名存储在 中~/.gitconfig)。

然后在你的壳里,

alias g=git
Run Code Online (Sandbox Code Playgroud)

你会发现g setc. 像你期望的那样工作,包括参数。