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

后端 未结 8 924
囚心锁ツ
囚心锁ツ 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:14

    Ravi's comment is essentially the answer. Functions take their own arguments. If you want them to be the same as the command-line arguments, you must pass them in. Otherwise, you're clearly calling a function without arguments.

    That said, you could if you like store the command-line arguments in a global array to use within other functions:

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

    You have to access the command-line arguments through the commandline_args variable, not $@, $1, $2, etc., but they're available. I'm unaware of any way to assign directly to the argument array, but if someone knows one, please enlighten me!

    Also, note the way I've used and quoted $@ - this is how you ensure special characters (whitespace) don't get mucked up.

提交回复
热议问题