簡體   English   中英

是否可以在bash中的命令之前執行數組分配?

[英]Is it possible to perform array assignment before a command in bash?

我正在嘗試將數組傳遞給shell腳本,如本問題所述 我編寫了一個小腳本,該腳本的設計目的只是為了接受數組的名稱並打印出數組:

#!/bin/bash
echo "$1"
echo "${!1}"
arrayVar=("${!1}")
echo "${arrayVar[1]}"

我在運行腳本時聲明了一個數組變量,如下所示:

array=(foo bar test) ./test.sh array[@]

輸出:

|array[@]         # the bars are only here to force the final blank line
|(foo bar test)
|

似乎array實際不是字符串,而只是字符串(foo bar test)

即使我修改腳本以直接按名稱而不是通過positional參數間接回顯array ,也可以得到相同的結果。

#!/bin/bash
echo "$1"
arrayVar=("${!1}")
echo $arrayVar
echo "${arrayVar[1]}"

echo $array
echo "${array[1]}"

輸出:

|array[@]         # the bars are only here to force the final blank line
|(foo bar test)
|
|(foo bar test)
|

我只是在做錯什么,還是bash在命令之前不支持數組分配?

似乎沒有任何支持。

如果array=(foo bar test) ./test.sh不這樣做( array被導出為文字字符串'(foo bar test)' ,則

array=(foo bar test); export array; ./test.sh

應該並且確實在導出之后,bash將數組報告為導出的數組( x表示已導出):

$ declare -p array
declare -ax array='([0]="foo" [1]="bar" [2]="test")'

但是事實證明這是一個謊言:

$ env | grep array; echo status=$?
  status=1

目前,bash不支持導出陣列。 這是在man bash

數組變量可能尚未導出。

暫無
暫無

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

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