簡體   English   中英

使用shell變量選擇一個bash數組

[英]Using a shell variable to choose one bash array

我正在嘗試編寫一個bash腳本,允許我在一組不同的數組中選擇一個數組 為此, 我打算使用一個簡單的變量來引用一個數組。

#!/bin/bash
#To get all the members of a given array as the output
#variables
FIRST=(A B C D)
SECOND=(planes cars trains bicycles gocarts)
THIRD=(werewolfs vampires zombies ghosts daemons)
FOURTH=(football soccer basketball rugby batmington zumo)
FIFTH=(handguns rifles machineguns bazookas slingshots)
SIXTH=(dogs cats turtles ferrets birds hamsters fish)
SEVENTH=(monday tuesday wednesday thursday friday saturday sunday)

#execution
select ARRAY in "FIRST" "SECOND" "THIRD" "FOURTH" "FIFTH" "SIXTH" "SEVENTH"; do 
    OUTPUT=eval '"${'${ARRAY}'[@]}"'
    echo $OUTPUT
    break 
done

#end

上面的腳本不起作用 到目前為止,我試圖用這些選項替換第9行

OUTPUT=eval '$'{ARRAY'[@]'}
OUTPUT=eval ${"$ARRAY"[@]}
OUTPUT=eval ${'$ARRAY'[@]}
OUTPUT=eval ${'$'ARRAY[@]}
OUTPUT=eval '$'{"$ARRAY"[@]}
OUTPUT=eval \${${ARRAY}[@]}

我在這里錯過了什么?

這對我有用:

#!/bin/bash
#To get all the members of a given array as the output
#variables
FIRST=(A B C D)
SECOND=(planes cars trains bicycles gocarts)
THIRD=(werewolfs vampires zombies ghosts daemons)
FOURTH=(football soccer basketball rugby batmington zumo)
FIFTH=(handguns rifles machineguns bazookas slingshots)
SIXTH=(dogs cats turtles ferrets birds hamsters fish)
SEVENTH=(monday tuesday wednesday thursday friday saturday sunday)

#execution
ARRAY="FIFTH"
select ARRAY in "FIRST" "SECOND" "THIRD" "FOURTH" "FIFTH" "SIXTH" "SEVENTH"; do
    eval "OUTPUT=\${$ARRAY[*]}"
    echo $OUTPUT
    break
done

eval可用於引入新變量。 我們構造一個字符串,其中包含為OUTPUT指定所需值的表達式,然后對其進行評估,從而引入一個具有所需值的新變量OUTPUT

eval絕對沒有必要解決這個問題。 在使用eval之前,你應該總是三思而后行,因為它很脆弱。 (也就是說,錯誤會帶來災難性的后果。)

這是“傳統”解決方案,它使用了! 間接語法。 它仍然有些脆弱,但沒有eval那么糟糕:

select array in "FIRST" "SECOND" "THIRD" "FOURTH" "FIFTH" "SIXTH" "SEVENTH"; do
  if [[ $array ]]; then
    # Indirection requires the full subscript to be included
    # in the variable which is used to indirect. "${!array[@]}"
    # would be "0", because that is not indirect syntax; rather it
    # is "array keys" syntax.
    array_at="$array"[@]
    echo "${!array_at}"
    break
  else
    echo "Invalid input; try again" >> /dev/stderr
  fi
done

從bash 4.3開始,你可以使用引用聲明,這使得上面的內容不那么笨重:

select name in "FIRST" "SECOND" "THIRD" "FOURTH" "FIFTH" "SIXTH" "SEVENTH"; do
  if [[ $name ]]; then
    declare -n array=name
    echo "${array[@]}"
    break
  else
    echo "Invalid input; try again" >> /dev/stderr
  fi
done
# Unless the user exits the select by typing an EOF,
# then `array` is now effectively a synonym
# for whichever of the arrays was selected.

我知道了。 以下適用於第9行

OUTPUT=$(eval echo \${${ARRAY}[@]})

非常感謝你對這個可憐的小學徒的耐心:)

暫無
暫無

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

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