簡體   English   中英

Shell 腳本:將關聯數組傳遞給另一個 shell 腳本

[英]Shell script: Pass associative array to another shell script

我想將關聯數組作為單個參數傳遞給 shell 腳本。

mainshellscript.sh:

#!/bin/bash
declare -A cmdOptions=( [branch]=testing [directory]=someDir [function1key]=function1value [function1key]=function1value )
./anothershellscript.sh cmdOptions

另一個shellscript.sh:

#!/bin/bash
#--- first approach, didn't work, shows error "declare: : not found"
#opts=$(declare -p "$1")
#declare -A optsArr=${opts#*=}
#---
# second approach, didnt work, output - declare -A optsArr=([0]="" )
#declare -A newArr="${1#*=}"
#declare -p newArr
#---

我懷疑他們在 anothershellscript.sh 中收集數組的方式是錯誤的,我正在尋找一種方法來訪問 map 值,只需提供echo "${optsArr[branch]}" shall give testing

我正在使用 bash 版本 4.4.23(1)-release (x86_64-pc-msys)。

進程是獨立的——它們共享變量。 在一個進程中設置的變量在另一個進程中不可見。 例外:子進程繼承導出的變量,但cmdOptions未導出,並且無論如何您都無法導出關聯的 arrays。

因此,通過 arguments 或使用文件或導出變量將數組的字符串表示形式傳遞給子項:

#!/bin/bash
declare -A cmdOptions=( [branch]=testing [directory]=someDir [function1key]=function1value [function1key]=function1value )

export SOME_VAR="$(declare -p cmdOptions)"              # env or
declare -p cmdOptions > some_file.txt                   # file or
./anothershellscript.sh "$(declare -p cmdOptions)"      # arg
# Note - `declare -p` is called _on parent side_!

然后加載孩子:

#!/bin/bash
declare -A newArr="${SOME_VAR#*=}"      # env or
. some_file.txt                         # file or
declare -A newArr="${1#*=}"             # arg

# How to load from file so that current environment is not affected:
tmp=$(
   . some_file.txt
   declare -p cmdOptions
)
declare -A newArr=${tmp#*=}" 

將關聯數組傳遞給子腳本

關聯的 arrays 和常規 arrays 不能很好地導出。 但是您可以通過在某些包裝器調用中使用declare -p來傳遞變量。

第一個腳本:

#!/bin/bash
declare -A cmdOptions=( [branch]=testing     [function1key]=function1value
                        [directory]=someDir  [function2key]=function2value )
declare -a someArray=( foo "bar baz" )

declare -x someVariable="Foo bar baz"    # Using *export* for simple variables

bash -c "$(declare -p cmdOptions someArray);. anothershellscript.sh"

注意語法. anothershellscript.sh . anothershellscript.sh可以替換為source anothershellscript.sh

這樣做,防止需要臨時文件或臨時變量並保持STDIN/STDOUT自由。

然后您的anothershellscript.sh可以按原樣使用您的變量。

#!/bin/bash

declare -p cmdOptions someArray someVariable

可以工作。

您必須在第二個腳本中重建該數組,這是一個示例 script1:

#!/bin/bash
declare -A test=(
    [v1]=1
    [v2]=2
    [v3]=3
)

for key in "${!test[@]}"; { data+=" $key=${test[$key]}"; }
echo "$data" | ./test2

腳本2:

#!/bin/bash
read   -ra data
declare -A test2

for item in "${data[@]}"; {
    key="${item%=*}"
    val="${item#*=}"
    test2[$key]="$val"
}
echo "${test2[@]}"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM