How to get the nth positional argument in bash?

后端 未结 4 1447
傲寒
傲寒 2020-12-07 13:03

How to get the nth positional argument in Bash, where n is variable?

相关标签:
4条回答
  • 2020-12-07 13:38

    Read

    Handling positional parameters

    and

    Parameter expansion

    $0: the first positional parameter

    $1 ... $9: the argument list elements from 1 to 9

    0 讨论(0)
  • 2020-12-07 13:41

    If N is saved in a variable, use

    eval echo \${$N}
    

    if it's a constant use

    echo ${12}
    

    since

    echo $12
    

    does not mean the same!

    0 讨论(0)
  • 2020-12-07 13:46

    As you can see in the Bash by Example, you just need to use the automatic variables $1, $2, and so on.

    $# is used to get the number of arguments.

    0 讨论(0)
  • 2020-12-07 14:01

    Use Bash's indirection feature:

    #!/bin/bash
    n=3
    echo ${!n}
    

    Running that file:

    $ ./ind apple banana cantaloupe dates
    

    Produces:

    cantaloupe
    

    Edit:

    You can also do array slicing:

    echo ${@:$n:1}
    

    but not array subscripts:

    echo ${@[n]}  #  WON'T WORK
    
    0 讨论(0)
提交回复
热议问题