How to pass an array argument to the Bash script

后端 未结 4 1227
猫巷女王i
猫巷女王i 2020-11-29 05:42

It is surprising me that I do not find the answer after 1 hour search for this. I would like to pass an array to my script like this:

test.sh argument1 array         


        
相关标签:
4条回答
  • 2020-11-29 06:18

    Bash arrays are not "first class values" -- you can't pass them around like one "thing".

    Assuming test.sh is a bash script, I would do

    #!/bin/bash
    arg1=$1; shift
    array=( "$@" )
    last_idx=$(( ${#array[@]} - 1 ))
    arg2=${array[$last_idx]}
    unset array[$last_idx]
    
    echo "arg1=$arg1"
    echo "arg2=$arg2"
    echo "array contains:"
    printf "%s\n" "${array[@]}"
    

    And invoke it like

    test.sh argument1 "${array[@]}" argument2
    
    0 讨论(0)
  • 2020-11-29 06:18

    Have your script arrArg.sh like this:

    #!/bin/bash
    
    arg1="$1"
    arg2=("${!2}")
    arg3="$3"
    arg4=("${!4}")
    
    echo "arg1=$arg1"
    echo "arg2 array=${arg2[@]}"
    echo "arg2 #elem=${#arg2[@]}"
    echo "arg3=$arg3"
    echo "arg4 array=${arg4[@]}"
    echo "arg4 #elem=${#arg4[@]}"
    

    Now setup your arrays like this in a shell:

    arr=(ab 'x y' 123)
    arr2=(a1 'a a' bb cc 'it is one')
    

    And pass arguments like this:

    . ./arrArg.sh "foo" "arr[@]" "bar" "arr2[@]"
    

    Above script will print:

    arg1=foo
    arg2 array=ab x y 123
    arg2 #elem=3
    arg3=bar
    arg4 array=a1 a a bb cc it is one
    arg4 #elem=5
    

    Note: It might appear weird that I am executing script using . ./script syntax. Note that this is for executing commands of the script in the current shell environment.

    Q. Why current shell environment and why not a sub shell?
    A. Because bash doesn't export array variables to child processes as documented here by bash author himself

    0 讨论(0)
  • 2020-11-29 06:19

    If this is your command:

    test.sh argument1 ${array[*]} argument2
    

    You can read the array into test.sh like this:

    arg1=$1
    arg2=${2[*]}
    arg3=$3
    

    It will complain at you ("bad substitution"), but will work.

    0 讨论(0)
  • 2020-11-29 06:31

    You can write your array to a file, then source the file in your script. e.g.:

    array.sh

    array=(a b c)
    

    test.sh

    source $2
    ...
    

    Run the test.sh script:

    ./test.sh argument1 array.sh argument3
    
    0 讨论(0)
提交回复
热议问题