shell 重载Bash命令:向原始二进制文件传递参数不起作用[重复]

v440hwme  于 2023-04-07  发布在  Shell
关注(0)|答案(1)|浏览(140)

此问题已在此处有答案

Propagate all arguments in a Bash shell script(12个回答)
Accessing bash command line args $@ vs $*(5个答案)
昨天关门了。
我正在编写一个简单的bash脚本来为git status添加一些额外的功能。目前,我正在通过将以下脚本(名为git)添加到我的路径来实现这一点:

#!/bin/bash

# Simple script to automatically configure user info between multiple repositories
#  by overloading the functionality of 'git status'
if [[ "$1" == "status" ]]; then
    # do something extra, then run vanilla 'git status'
    /usr/bin/git status
else
    # behave normally
    /usr/bin/git $@
fi

当我输入git <any args>时,Bash会首先找到我的脚本git,所以它会运行它。我遇到的问题是else子句。显然,在这样的脚本中运行/usr/bin/git $@与从命令行运行它是不一样的。例如,当我运行git commit时:

$ git commit -m "Init HW4 Rust project" # runs the else branch of my script
error: pathspec 'HW4' did not match any file(s) known to git
error: pathspec 'Rust' did not match any file(s) known to git
error: pathspec 'project' did not match any file(s) known to git
$ /usr/bin/git commit -m "Init HW4 Rust project" # runs my standard git installation
On branch main
Your branch is ahead of 'origin/main' by 2 commits.
  (use "git push" to publish your local commits)

nothing to commit, working tree clean

我怀疑这与$@变量有关。据我所知,$@表示Bash脚本接收的所有命令行参数,除了第0个参数(命令)。这与显式键入参数有什么不同?

qxgroojn

qxgroojn1#

因为没有引用$@,所以得到的参数比预期的要多:

$ set -- commit -m "Init HW4 Rust project"
$ printf '%q\n' $@
commit
-m
Init
HW4
Rust
project

与正确引用的"$@"比较:

$ printf '%q\n' "$@"
commit
-m
Init\ HW4\ Rust\ project

相关问题