如何在函数内访问调用者的命令行参数?

问题描述 投票:82回答:7

我正在尝试在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 $*
bash command-line-arguments argv
7个回答
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

保存在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 

87
投票

如果你想要你的参数C style(参数数组+参数数量)你可以使用$@$#

$#为您提供了多少参数。 $@为您提供所有论据。您可以通过args=("$@")将其转换为数组。

例如:

args=("$@")
echo $# arguments passed
echo ${args[0]} ${args[1]} ${args[2]}

请注意,这里${args[0]}实际上是第一个参数,而不是脚本的名称。


15
投票

Ravi的评论基本上就是答案。函数采用自己的论点。如果您希望它们与命令行参数相同,则必须将它们传入。否则,您显然正在调用不带参数的函数。

也就是说,如果您喜欢将命令行参数存储在全局数组中以在其他函数中使用,则可以:

my_function() {
    echo "stored arguments:"
    for arg in "${commandline_args[@]}"; do
        echo "    $arg"
    done
}

commandline_args=("$@")

my_function

你必须通过commandline_args变量访问命令行参数,而不是$@$1$2等,但它们是可用的。我不知道有任何方法直接分配给参数数组,但如果有人知道,请赐教!

另外,请注意我使用和引用$@的方式 - 这是你如何确保特殊字符(空白)不被混淆。


12
投票
#!/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 $#

编辑:请参阅我对问题的评论


6
投票
# 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

2
投票

人们也可以这样做

#!/bin/bash
# script_name function_test.sh
function argument(){
for i in $@;do
    echo $i
done;
}
argument $@

现在调用你的脚本

./function_test.sh argument1 argument2

1
投票

您可以使用shift关键字(运算符?)来迭代它们。例:

#!/bin/bash
function print()
{
    while [ $# -gt 0 ]
    do
        echo $1;
        shift 1;
    done
}
print $*;
© www.soinside.com 2019 - 2024. All rights reserved.