【发布时间】:2011-02-14 00:23:48
【问题描述】:
我正在尝试在 bash 中编写一个可以访问脚本命令行参数的函数,但它们被替换为函数的位置参数。如果没有显式传入,函数有什么方法可以访问命令行参数?
# Demo function
function stuff {
echo $0 $*
}
# Echo's the name of the script, but no command line arguments
stuff
# Echo's everything I want, but trying to avoid
stuff $*
【问题讨论】:
-
我有点困惑,你想要 args 而不传递它们?
-
是的,关键是从函数内部获取命令行参数,而不将它们作为函数参数传递。它与错误处理情况有关,在这种情况下,我想根据命令行参数进行错误处理,而与传递给函数的参数无关。
-
仅供参考,
$*非常有问题——它会将./yourScript "first argument" "second argument"更改为./yourscript "first" "argument" "second" "argument",或者将./yourscript '*.txt'更改为./yourscript one.txt two.txt之类的东西,尽管有引号。
标签: bash command-line-arguments argv