如何访问函数内调用者的命令行参数? [英] How to access command line arguments of the caller inside a function?

查看:26
本文介绍了如何访问函数内调用者的命令行参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用 bash 编写一个函数来访问脚本命令行参数,但它们被替换为函数的位置参数.如果没有显式传入命令行参数,函数有什么方法可以访问它们吗?

I'm attempting to write a function in bash that will access the scripts command line arguments, but they are replaced with the positional arguments to the function. Is there any way for the function to access the command line arguments if they aren't passed in explicitly?

# 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 参考手册 说这些内容是在 BASH_ARGV,虽然它谈到了堆栈"很多.

My reading of the Bash Reference Manual says this stuff is captured in BASH_ARGV, although it talks about "the stack" a lot.

#!/bin/bash

shopt -s extdebug

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
fbaz bar boo arg2 arg1 arg0
g goo gar gaz
ggaz gar goo arg2 arg1 arg0
f
fgaz gar goo arg2 arg1 arg0

这篇关于如何访问函数内调用者的命令行参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆