在bash,你如何访问一个函数内部命令行参数? [英] In Bash, how do you access command line arguments inside a function?

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

问题描述

我试图写在bash将访问脚本的命令行参数的功能,但它们与位置参数的函数代替。有没有什么办法的函数访问命令行参数,如果他们不明确的通过呢?

 #演示功能
功能的东西{
  回声$ 0 $ *
}#回波脚本的名称,但没有命令行参数
东东#Echo的一切我想要的,但尽量避免
东西$ *


解决方案

我在bash参考手册的可读性说,这东西是在BASH_ARGV抓获,
虽然谈到栈了许多。

 #!/斌/庆典函数的argv {
    对于在$ {BASH_ARGV [*]};做
      回声-n$ A
    DONE
    回声
}函数f {
    回声F $ 1 $ 2 $ 3
    呼应-n F; ARGV
}函数g {
    回声G $ 1 $ 2 $ 3
    呼应-n克; ARGV
    F
}˚F嘘吧巴兹
摹咕噶尔GAZ

保存f.sh

  $ ./f.sh为arg0 ARG1 ARG2
˚F嘘吧巴兹
farg2 ARG1为arg0
摹咕噶尔GAZ
garg2 ARG1为arg0
F
farg2 ARG1为arg0

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 $*

解决方案

My reading of the bash ref manual says this stuff is captured in BASH_ARGV, although it talks about "the stack" a lot.

#!/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

Save in 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 

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

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