Results 1 to 3 of 3

Thread: expansion of $@ in a script

  1. #1
    Join Date
    Jun 2010
    Beans
    380

    Arrow expansion of $@ in a script

    I have come across a small script as follows

    Code:
    declare -a args=( "$@" ) echo ${#args[@]}  #
    
    this is being run as
    bash demo1.sh *.pdf

    where it is being checked how many pdfs are there in the directory.

    I read the man page of bash which says
    An indexed array is created automatically if any variable is assigned to using the syntax name[subscript]=value. The subscript is treated
    as an arithmetic expression that must evaluate to a number. If subscript evaluates to a number less than zero, it is used as an offset
    from one greater than the array's maximum index (so a subcript of -1 refers to the last element of the array). To explicitly declare an
    indexed array, use declare -a name (see SHELL BUILTIN COMMANDS below). declare -a name[subscript] is also accepted; the subscript is
    ignored.

    I am not clear with 2 things
    Code:
    declare -a args=( "$@" )
    what does this means? and what it gets evaluated to what does ("$@") mean and in the second line what does
    Code:
     echo ${#args[@]}  #
    gets expanded to?what is meant by ${}and args[@] expands to what

  2. #2
    Join Date
    Apr 2012
    Beans
    7,099

    Re: expansion of $@ in a script

    The @ mean different things depending on the context

    args=( "$@" )
    constructs an array called args from the script's argument list $@

    See http://tldp.org/LDP/abs/html/interna...es.html#APPREF

    ${#args[@]} is shorthand for the number of elements in the array called args

    See http://tldp.org/LDP/abs/html/arrays.html

  3. #3
    Join Date
    Jul 2007
    Location
    Poland
    Beans
    4,499
    Distro
    Ubuntu 14.04 Trusty Tahr

    Re: expansion of $@ in a script

    in case one only wants to get the number of parameters, array is somewhat roundabout way to achieve that. The number of parameters script/function gets is directly accessible with $#

    Code:
    $ args() { echo $#; arg=( "$@" ); echo ${#arg[@]}; }
    $ args *.sh
    69
    69
    if your question is answered, mark the thread as [SOLVED]. Thx.
    To post code or command output, use [code] tags.
    Check your bash script here // BashFAQ // BashPitfalls

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •