How the shell uses an array as a function parameter __ function

Source: Internet
Author: User

Because of the need to use the shell to develop a number of gadgets, when using an array as a function parameter, found that only the first element of the array can be passed, the elements behind the array can not be passed into the function.

#!/bin/bash

function Showarr () {

    arr=$1 for I-in

    ${arr[*]}; does
        echo $i done

}

regions= (" GZ "" SH "" BJ "

showarr $regions

exit 0

After the code is saved as test.sh, only the first element is exported.

./test.sh
GZ

To get the first argument of the function, and the first argument of the function is the regions array, it's strange why you can only get the first element of the array.


After testing,

Echo $regions

Only the first element is output, so using regions as a parameter passes only the first element.

Therefore, the argument needs to be written "${regions[*]}" to be passed as an array.


The code is modified as follows:

#!/bin/bash

function Showarr () {

    arr=$1 for I-in

    ${arr[*]}; does
        echo $i done

}

regions= ("GZ" "SH" "BJ")

Showarr "${regions[*]}"

exit 0

After running all elements of an array, the array can be passed as a function parameter after modification.

./test.sh
GZ
sh
BJ
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.