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

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

    You can use the shift keyword (operator?) to iterate through them. Example:

    #!/bin/bash
    function print()
    {
        while [ $# -gt 0 ]
        do
            echo $1;
            shift 1;
        done
    }
    print $*;
    
    0 讨论(0)
  • 2020-11-28 08:35

    If you want to have your arguments C style (array of arguments + number of arguments) you can use $@ and $#.

    $# gives you the number of arguments.
    $@ gives you all arguments. You can turn this into an array by args=("$@").

    So for example:

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

    Note that here ${args[0]} actually is the 1st argument and not the name of your script.

    0 讨论(0)
提交回复
热议问题