Don*_*Gar 89 bash argv command-line-arguments
我正在尝试在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 $*
Run Code Online (Sandbox Code Playgroud)
sti*_*igi 87
如果你想要你的参数C style(参数数组+参数数量)你可以使用$@和$#.
$#给你参数的数量.
$@给你所有的论据.您可以将其转换为数组args=("$@").
例如:
args=("$@")
echo $# arguments passed
echo ${args[0]} ${args[1]} ${args[2]}
Run Code Online (Sandbox Code Playgroud)
请注意,这里${args[0]}实际上是第一个参数,而不是脚本的名称.
mca*_*fio 43
我阅读bash参考手册说这些东西是在BASH_ARGV中捕获的,尽管它很多地讨论了"堆栈".
#!/bin/bash
function argv {
for a in ${BASH_ARGV[*]} ; do
echo -n "$a "
done
echo
}
function f {
echo f $1 $2 $3
echo -n f ; argv
}
function g {
echo g $1 $2 $3
echo -n g; argv
f
}
f boo bar baz
g goo gar gaz
Run Code Online (Sandbox Code Playgroud)
保存在f.sh中
$ ./f.sh arg0 arg1 arg2
f boo bar baz
farg2 arg1 arg0
g goo gar gaz
garg2 arg1 arg0
f
farg2 arg1 arg0
Run Code Online (Sandbox Code Playgroud)
Cas*_*bel 15
Ravi的评论基本上就是答案.函数采用自己的论点.如果您希望它们与命令行参数相同,则必须将它们传入.否则,您显然正在调用不带参数的函数.
也就是说,如果您喜欢将命令行参数存储在全局数组中以在其他函数中使用,则可以:
my_function() {
echo "stored arguments:"
for arg in "${commandline_args[@]}"; do
echo " $arg"
done
}
commandline_args=("$@")
my_function
Run Code Online (Sandbox Code Playgroud)
你必须通过访问命令行参数commandline_args变量,而不是$@,$1,$2等,但他们提供.我不知道有任何方法直接分配给参数数组,但如果有人知道,请赐教!
另外,请注意我使用和引用的方式$@- 这是你如何确保特殊字符(空白)不会被破坏.
Rav*_*yas 13
#!/usr/bin/env bash
echo name of script is $0
echo first argument is $1
echo second argument is $2
echo seventeenth argument is $17
echo number of arguments is $#
Run Code Online (Sandbox Code Playgroud)
编辑:请参阅我对问题的评论
# Save the script arguments
SCRIPT_NAME=$0
ARG_1=$1
ARGS_ALL=$*
function stuff {
# use script args via the variables you saved
# or the function args via $
echo $0 $*
}
# Call the function with arguments
stuff 1 2 3 4
Run Code Online (Sandbox Code Playgroud)