How to access command line arguments of the caller inside a function?

后端 未结 8 927
囚心锁ツ
囚心锁ツ 2020-11-28 07:31

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 ther

8条回答
  •  没有蜡笔的小新
    2020-11-28 08:24

    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 
    

提交回复
热议问题